2011-07-30 78 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.