Search code examples
c#linqmorelinq

Best way to rewrite a groupby / orderby query in LINQ to objects


I have some data looking like this :

Environment | Time
"1" | 2021/09/01
"2" | 2021/09/02
"1" | 2021/09/03
"3" | 2021/09/01
"1" | 2021/09/03
"1" | 2021/09/04
"3" | 2021/12/01
"2" | 2021/11/02

I need to find the last record (by time) for each environment, so I wrote :

var lastPerEnvironment = data
    .GroupBy(prp => prp.Environment)
    .Select(prp => prp.OrderByDescending(o => o.Time).First());

Of course it works as expected, but I guess there's a simpler way to write it and maybe also more efficient, using a convening library like MoreLINQ for example (or another good to know library ?), with some kind of partitioning.

I do not need the Linq to SQL translation (but it would be nice if it was also supported by the suggested solution), only Linq to Objects.

Thanks for suggestions


Solution

  • You can refer to this SO response: optimize your prp.OrderByDescending(o => o.Time).First() by MaxBy(o => o.Date); (native in .NET 6 but also available in MoreLINQ)