查找具有最大值的列表中的项目

时间:2016-02-09 20:47:23

标签: vb.net list max

我是VB.Net的初学者。在我正在处理的代码中,有一个名为Market的类,其属性为Demand(整数)。我已经列出了所有Market的实例。在代码中的某个时刻,我需要在列表中找到具有最高需求值的Market实例。我怎样才能有效地做到这一点(没有循环遍历列表中的所有成员并将其需求与找到的最低值进行比较)。 谢谢您的帮助 美好的一天!

2 个答案:

答案 0 :(得分:7)

您可以使用OrderByDescending方法按需要属性对List进行排序,然后选择第一项。

    Dim markets As New List(Of Market)
    markets.Add(New Market With {.Demand = 10})
    markets.Add(New Market With {.Demand = 30})
    markets.Add(New Market With {.Demand = 20})
    Dim topMarket As Market = markets.OrderByDescending(Function(m) m.Demand).FirstOrDefault

答案 1 :(得分:2)

使用Linq。这是一个小例子。我试图使用您指定的变量名称。不确定你叫什么名单,所以我只称它为MarketList

Public Class Form1
Private MarketList As List(Of Market)
Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()
    MarketList = New List(Of Market)()
    ' Add any initialization after the InitializeComponent() call.
    RunIt()
End Sub
Private Sub RunIt()
    Dim oMarket As New Market()
    oMarket.Demand = 0
    MarketList.Add(oMarket)
    oMarket = New Market()
    oMarket.Demand = 1
    MarketList.Add(oMarket)
    oMarket = New Market()
    oMarket.Demand = 2
    MarketList.Add(oMarket)

    Dim oMax As Market = (From mrkt As Market In MarketList Select mrkt Order By mrkt.Demand).Last()
    MessageBox.Show(String.Format("Market List has: {0} members" + vbNewLine + "Maximum Demand: {1}", MarketList.Count.ToString(), iMax.Demand.ToString()))
End Sub
Public Class Market
    Private _dmd As Integer
    Public Property Demand() As Integer
        Get
            Return _dmd
        End Get
        Set(ByVal value As Integer)
            _dmd = value
        End Set
    End Property

End Class

我根据您的要求编辑了它。你接受的答案基本上是做同样的事情,只是略有不同。无论如何,这里有你或其他人的替代选择。