vb.net 在列表中查找具有最大值的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35301862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding an item in a list with maximum value
提问by Helia
I m a beginner in VB.Net. In the code I m working on, there is a class called Market with an attribute of Demand (integer). I have made a list of all instances of Market. At some point in the code, I need to find the Market instance in the list with highest demand value. How can I do that efficiently (without looping over all members of the list and comparing their demand with the lowest found value). Thank you for your help Good day!
我是 VB.Net 的初学者。在我正在处理的代码中,有一个名为 Market 的类,其属性为 Demand(整数)。我已经列出了 Market 的所有实例。在代码中的某个点,我需要在列表中找到需求值最高的 Market 实例。我怎样才能有效地做到这一点(无需遍历列表的所有成员并将他们的需求与找到的最低值进行比较)。感谢您的帮助 美好的一天!
回答by Blackwood
You can use the OrderByDescendingmethod to sort the Listby the Demand property and then select the first item.
您可以使用该OrderByDescending方法List按 Demand 属性对 进行排序,然后选择第一项。
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
回答by Aaron
Use Linq. Here's a small example. I tried to use the variable names you specified. Not sure what you called your list, so I just called it MarketList
使用 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
I edited it per your request. You're basically doing the same thing the answer you accepted is doing, just in a slightly different way. Anyway, here's an alternative for you or someone else that comes along.
我根据你的要求编辑了它。您基本上在做与您接受的答案相同的事情,只是方式略有不同。无论如何,这是您或其他人的替代方案。

