如何让 LINQ 返回具有给定属性最大值的对象? [英] How can I get LINQ to return the object which has the max value for a given property?
本文介绍了如何让 LINQ 返回具有给定属性最大值的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个看起来像这样的类:
If I have a class that looks like:
public class Item
{
public int ClientID { get; set; }
public int ID { get; set; }
}
还有这些物品的集合...
And a collection of those items...
List<Item> items = getItems();
如何使用 LINQ 返回具有最高 ID 的单个Item"对象?
How can I use LINQ to return the single "Item" object which has the highest ID?
如果我这样做:
items.Select(i => i.ID).Max();
我只会得到最高的 ID,当我真正想要返回的是具有最高 ID 的 Item 对象本身时?我希望它返回一个Item"对象,而不是一个 int.
I'll only get the highest ID, when what I actually want returned is the Item object itself which has the highest ID? I want it to return a single "Item" object, not an int.
推荐答案
这只会循环一次.
Item biggest = items.Aggregate((i1,i2) => i1.ID > i2.ID ? i1 : i2);
谢谢尼克 - 这是证据
Thanks Nick - Here's the proof
class Program
{
static void Main(string[] args)
{
IEnumerable<Item> items1 = new List<Item>()
{
new Item(){ ClientID = 1, ID = 1},
new Item(){ ClientID = 2, ID = 2},
new Item(){ ClientID = 3, ID = 3},
new Item(){ ClientID = 4, ID = 4},
};
Item biggest1 = items1.Aggregate((i1, i2) => i1.ID > i2.ID ? i1 : i2);
Console.WriteLine(biggest1.ID);
Console.ReadKey();
}
}
public class Item
{
public int ClientID { get; set; }
public int ID { get; set; }
}
重新排列列表并得到相同的结果
Rearrange the list and get the same result
这篇关于如何让 LINQ 返回具有给定属性最大值的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文