【问题标题】:Min and max from list collection列表集合中的最小值和最大值
【发布时间】:2017-01-12 03:19:25
【问题描述】:

如何从这个例子中得到最小值和最大值

Public Class RowsFound
    Property RowIndex As integer
    Property Qty As Integer
    Property LineValue As Double
End Class
Dim Test as new List(Of RowsFound)

您可以在上面看到我的列表的结构。这就是数据的样子。

根据最大 LineValue 和 Min LineValue 的 RowIndex 获取 RowIndex 的最佳方法是什么

我已将其作为测试,但想看看是否有更好的方法。

                        Dim MaxRow As Integer = 0
                        Dim MaxRowValue As Integer = 0
                        Dim MinRow As Integer = 999999
                        Dim MinRowValue As Integer = 999999
                        For Each MinMaxitem As RowsFound In ListOfRows
                            If MinMaxitem.LineValue < MinRowValue Then
                                MinRow = MinMaxitem.RowIndex
                                MinRowValue = MinMaxitem.LineValue
                            End If
                            If MinMaxitem.LineValue > MaxRowValue Then
                                MaxRow = MinMaxitem.RowIndex
                                MaxRowValue = MinMaxitem.LineValue
                            End If
                        Next

谢谢你:)

【问题讨论】:

  • 你尝试过什么吗? “最好”是什么意思?最少的代码?执行速度最快?最容易维护?
  • 是的,我会说最少和最快的将是完美的。 :)

标签: vb.net ienumerable


【解决方案1】:

您可以使用 Lambda 表达式:

  1. 首先使用Max()Min()找到LineValue的最大值\最小值

  2. 使用FindIndex()查找所需值的索引

    Private Function getMaxValueIndex() As Integer
    Dim maxValue As Integer = Test.Max(Function(t) t.LineValue)
    Dim maxValueIndex As Integer = Test.FindIndex(Function(t) t.LineValue = maxValue)
    Return maxValueIndex
    End Function
    
    Private Function getMinValueIndex() As Integer
    Dim minValue As Integer = Test.Min(Function(t) t.LineValue)
    Dim minValueIndex As Integer = Test.FindIndex(Function(t) t.LineValue = minValue)
    Return minValueIndex
    End Function
    

【讨论】:

    【解决方案2】:

    一个简单的方法是使用 LINQ:

    Public Class RowsFound
        Property RowIndex As Integer
        Property Qty As Integer
        Property LineValue As Double
        Public Sub New(i As Integer, q As Integer, v As Double)
            Me.RowIndex = i
            Me.Qty = q
            Me.LineValue = v
        End Sub
    End Class
    Dim Test As New List(Of RowsFound) From {New RowsFound(0, 1, 105.25), New RowsFound(1, 2, 100), New RowsFound(2, 1, 110), New RowsFound(3, 2, 60.25)}
    
    
    Dim RowIndexMax As Integer = (From row As RowsFound In Test.OrderByDescending(Function(x) x.LineValue) Select row.RowIndex).First
    Dim RowindexMin As Integer = (From row As RowsFound In Test.OrderBy(Function(x) x.LineValue) Select row.RowIndex).First
    

    【讨论】:

      猜你喜欢
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多