How to find item with max value using linq?

user1784622 picture user1784622 · Mar 7, 2013 · Viewed 117.4k times · Source

Have a look at the below table:

Item          Value
A                10
b                50
c                90

I want to find the item with maximum value. I can get that by using group by or orderding, but somehow I have a feeling there should be a more direct way. Am I right?

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Mar 7, 2013

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);