2

我有一个特定类的列表。在此列表中,包含一个职位类别。该位置类包括 X 和 Y 坐标。我有当前坐标和列表中的坐标。我想计算 List 中每个项目的距离并找出哪个项目的距离最小。这是我的代码:

  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

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

谢谢你。

4

3 回答 3

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 中有关 Linq 的一些信息和示例,请参阅http://msdn.microsoft.com/en-us/vbasic/bb688088

于 2011-07-30T12:43:59.720 回答
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
于 2011-07-30T12:46:55.257 回答
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.
于 2011-07-30T17:36:18.477 回答