我怎样才能得到LINQ返回具有给定属性最大值的对象吗? [英] How can I get LINQ to return the object which has the max value for a given property?

查看:253
本文介绍了我怎样才能得到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?

How can I use LINQ to return the single "Item" object which has the highest ID?

如果我做这样的事情:

items.Select(i => i.ID).Max(); 

我只得到最高的ID,当什么其实我是想回来是Item对象本身具有最高ID?我希望它返回一个项目对象,而不是一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆