【问题标题】:To find min. value in a list in vb.net找到分钟。 vb.net 列表中的值
【发布时间】:2011-07-31 01:36:18
【问题描述】:

我有一个特定班级的列表。 在此列表中,包含一个职位类别。 该位置类包括 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

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

谢谢。

【问题讨论】:

    标签: vb.net list max distance min


    【解决方案1】:

    在 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

    【讨论】:

      【解决方案2】:

      为最小值创建一个变量,并根据循环中的每个值检查它。

      您应该从循环外的控件中解析文本,在循环内一遍又一遍地这样做是一种浪费。您还应该打开严格模式,这样您就不会进行不应该是隐式的隐式转换。

      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
      

      【讨论】:

      • 感谢您的回答。我认为他们会提供帮助。
      【解决方案3】:

      以@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.
      

      【讨论】:

        猜你喜欢
        • 2013-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-01
        • 2011-12-06
        • 2014-10-22
        • 1970-01-01
        相关资源
        最近更新 更多