How can I get LINQ to return the object which has the max value for a given property?

FrankTheTank picture FrankTheTank · Jul 6, 2010 · Viewed 127.8k times · Source

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();

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

If I do something like:

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

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.

Answer

Seattle Leonard picture Seattle Leonard · Jul 6, 2010

This will loop through only once.

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