Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find item with max value using linq? [duplicate]

Tags:

c#

linq

max

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?

like image 804
user1784622 Avatar asked Mar 07 '13 07:03

user1784622


People also ask

How do you find the maximum value in Linq?

In LINQ, you can find the maximum element of the given sequence by using Max() function. This method provides the maximum element of the given set of values.

How do I remove duplicate values in Linq?

We can remove all duplicates like this by using GroupBy and Select methods provided by LINQ . First, we group our list so that we will create groups for each name in the List. Then we use Select to only select the first objects in each group. This will result in the removal of the duplicates.

How do you find the average in LINQ query?

In LINQ, you can find the average of the given sequence by using the Average method. This method returns the average of the elements present in the given sequence or collection. It returns nullable, non-nullable decimal, double, floats, int, etc. values.


1 Answers

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); 
like image 131
Sergey Berezovskiy Avatar answered Sep 17 '22 16:09

Sergey Berezovskiy