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?
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With