2011-07-30 56 views
2

列表值我有特定的类的列表。 在此列表中,包含职位类别。 这一立场类包括X和Y坐标。 我当前坐标,并在列表中的坐标。 我要计算在列表中的每个项目的距离,找到哪个项目有最小距离。 这里是我的代码:寻找最小。在vb.net

For Each item As ITEMX In xHandle.ItemList 

     Dim CurrX As Integer = txt_TrainX.Text 
     Dim CurrY As Integer = txt_TrainY.Text 
     Dim NextX As Integer = item.Position.x 
     Dim NextY As Integer = item.Position.y 

     Dim distance As Integer = DistanceBetween(CurrX, CurrY, NextX, NextY) 


    Next 

所以距离是我的坐标与项目之间的距离。 我计算它在列表中的每个项目,但如何找到最小呢?

谢谢。

回答

1

创建极小值的变量,并检查它针对每个值循环。

你应该分析从外循环的控件中的文本,这是到了做,一遍又一遍的循环中的浪费。您还应该打开严格模式,以便您不要进行不应隐式的隐式转换。

Dim minimal As Nullable(Of Integer) = Nothing 

Dim CurrX As Integer = Int32.Parse(txt_TrainX.Text) 
Dim CurrY As Integer = Int32.Parse(txt_TrainY.Text) 

For Each item As ITEMX In xHandle.ItemList 

    Dim NextX As Integer = item.Position.x 
    Dim NextY As Integer = item.Position.y 

    Dim distance As Integer = DistanceBetween(CurrX, CurrY, NextX, NextY) 

    If Not minimal.HasValue or distance < minimal.Value Then 
    minimal.Value = distance 
    End If 

Next 
+0

感谢asnwers.I认为他们会帮助。 – sarkolata

3

在VB.NET使用LINQ:

Dim CurrX As Integer = txt_TrainX.Text 
Dim CurrY As Integer = txt_TrainY.Text 

Dim NearestITEM = xHandle.ItemList.Min (Function(i) DistanceBetween(CurrX, CurrY, i.Position.x, i.Position.y)); 

在VB.NET的一些资料和样品abount的LINQ看到http://msdn.microsoft.com/en-us/vbasic/bb688088

1

建立在@ Yahia的LINQ上回答了一下,以获得物品和物品的距离。

Dim CurrX = CInt(txt_TrainX.Text) 
Dim CurrY = CInt(txt_TrainY.Text) 

Dim itemsWithDistance = (From item in xHandle.ItemList 
         Select New With {.Item = item, 
              .Distance = DistanceBetween(CurrX, CurrY, item.Position.x, item.Position.y)}).ToList() 

' At this point you have a list of an anonymous type that includes the original items (`.Item`) and their distances (`.Distance`). 
' To get the one with the smallest distance you can do. 
Dim nearestItem = itemsWithDistance.Min(Function(i) i.Distance) 

' Then to see what that distance was, you can 
Console.WriteLine(nearestItem.Distance) 

' or you can access nearestItem.Item to get at the source item.