通用列表中的最小值和最大值 [英] Minimum and Maximum value from Generic List
问题描述
朋友们,
我有一个包含许多属性的酒店类.当我从数据库中检索所有酒店数据时,我将它们存储在通用列表"对象中.
现在,我想要两个属性,分别是LowestPrice和HiestPrice.我想直接从通用列表中获取Minimum(LowestPrice)和Maximum(HiestPrice).
类似于HotelList.Min();
现在,我在项目中实现了以下逻辑,但是我不想使用foreach循环.
Hi friends,
I have one Hotel class that contains many properties. When I retrieve all hotels data from database, I store them in Generic List object.
Now what I want that I have two properties called LowestPrice and HiestPrice. I want to get Minimum(LowestPrice) and Maximum(HiestPrice) from generic list directly.
Something like HotelList.Min();
Right now I have following logic implemented in my project, but I dont want to use foreach loop.
HotelController h1 = null;
HotelController h2 = null;
foreach (HotelController h in hList)
{
if (h1 == null && h2 == null)
{
h1 = h;
h2 = h;
continue;
}
if (h.CheapestRate < h1.CheapestRate)
{
h1 = h;
}
if (h.CheapestRate > h2.CheapestRate)
{
h2 = h;
}
}
minPrice = Convert.ToInt32(h1.CheapestRate.ToString());
maxPrice = Convert.ToInt32(h2.CheapestRate.ToString());
谢谢和问候
Imrankhan
Thanks and Regard
Imrankhan
推荐答案
如果您使用的是.net 2.0,则可能会有所帮助:
Hi,
If you are using .net 2.0 this might be helpful: http://stackoverflow.com/questions/152613/c-getting-maximum-and-minimum-values-of-arbitrary-properties-of-all-items-in-a[^]
L
我添加了对LinqBridge.dll的引用,并且我正在使用Framework 2.0,但仍然无法使用Linq方法.
我正在做这样的事情.
double d = hList.Max(l => l.CheapestRate);
但它告诉我无效的表达式>
I add reference for LinqBridge.dll and I am working on framework 2.0 but still I can''t able to use Linq method.
I am doing something like this.
double d = hList.Max(l => l.CheapestRate);
but it tells me invalid expression >
这篇关于通用列表中的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!