开发者

To find min. value in a list in vb.net

I have a list of specific class. In this list , a position class is included. And that position class includes X and Y coordinates. I have Current Coordinates and the coordinates in list . I want to calculate the distance for each item in List and find which item has minimal distance. Here is my code :

  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

so distance is the distance between my coordinates and the item. I calcul开发者_如何学JAVAate it for each item in list but how do i find the minimal one ?

Thank you.


Using Linq in VB.NET:

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));

for some information and samples abount Linq in VB.NET see http://msdn.microsoft.com/en-us/vbasic/bb688088


Create a variable for the minimal value, and check it against each value in the loop.

You should parse the text from the controls outside the loop, it's a waste to do that over and over again inside the loop. You should also turn on strict mode so that you don't do implicit conversions that shouldn't be implicit.

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


Building on @Yahia's LINQ answer a bit to both get the item and the item's distance.

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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜