Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Getting the row with the maximum value of a given attribute

I have a bunch of rows grouped on an attribute called MyID. Now I want the one row from each group where the StatusDate attribute is the highest in that one group.

This is what I've come up with.

rows.Select(x => x.Where(y => y.StatusDate == x.Max(z => z.StatusDate)).First())

With a bit more explanation:

rows.Select(x => // x is a group
  x.Where(y => // get all rows in that group where...
               // the status date is equal to the largest
               // status date in the group
    y.StatusDate == x.Max(z => z.StatusDate)
  ).First()) // and then get the first one of those rows

Is there any faster or more idiomatic way to do this?

like image 333
Deniz Dogan Avatar asked Dec 18 '09 07:12

Deniz Dogan


People also ask

How to get Max value using 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 to Find Max value in list c#?

The standard solution to get the minimum value in a sequence of values is using the Min() method. Similarly to get the maximum value, use the Max() method.

What is Max in LINQ?

Max () function in LINQ is used to return the maximum value from the collection. With the help of Max() function, it is easy to find the maximum value from a given data source using Max () function. In the other case, we have to write the code to get the maximum value from the list of values.


1 Answers

One alternative would be to use:

rows.Select(x => x.OrderByDescending(y => y.StatusDate).First());

... and check that the query optimiser knows that it doesn't really need to sort everything. (This would be disastrous in LINQ to Objects, but you could use MaxBy from MoreLINQ in that case :)

(Apologies for previous version - I hadn't fully comprehended the grouping bit.)

like image 104
Jon Skeet Avatar answered Oct 20 '22 01:10

Jon Skeet