列表集合中的最小值和最大值

时间:2016-09-04 16:16:13

标签: vb.net ienumerable

如何从此示例中获取最小值ad max值

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

你可以看到我的列表中的结构。这就是数据的样子。 enter image description here

根据Min LineValue的最大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

谢谢:)

2 个答案:

答案 0 :(得分:2)

您可以使用Lambda表达式:

  1. 首先使用LineValueMax()

  2. 找到Min()的最大\最小值
  3. 使用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
    

答案 1 :(得分:0)

一种简单的方法是使用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
相关问题