Is it possible to do a Group By in LINQ but then only return the 'most recent' item (per group)?

StackOverflow https://stackoverflow.com/questions/17650148

  •  03-06-2022
  •  | 
  •  

Question

I'm trying to return the most recent item, per group, in .NET LINQ.

It reminds me of doing a PARTITION in Sql where we partition and get the top 1 per partition, ordered by most recent (per partition).

So far I've got the start of the linq code..

from p in products
group p by new {p.Provider.ProductId, p.Provider.Name} into g

But i'm not sure how to add the order by p.CreatedOn desc and just get the .Take(1), per partition/group.

Was it helpful?

Solution

Something like (appended at the end of your query):

select new {
    g.Key,
    Product = g.OrderByDescending(x => x.CreatedOn).First()
}

should do the job; or perhaps more conveniently:

select new {
    g.Key.ProductId,
    g.Key.Name,
    Product = g.OrderByDescending(x => x.CreatedOn).First()
}

Or if you don't need the key explicitly (because it is available under the item anyway), then just:

select g.OrderByDescending(x => x.CreatedOn).First()

Basically, each g is an IGrouping<T> (for some anonymous T), which means each g has a .Key property that is your group, and each g is an IEnumerable<> sequence of the original elements (presumably Product).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top