c# - Is it possible to do a Group By in LINQ but then only return the 'most recent' item (per group)? -
i'm trying return recent item, per group, in .net linq.
it reminds me of doing partition in sql partition , top 1 per partition, ordered recent (per partition).
so far i've got start of linq code..
from p in products group p new {p.provider.productid, p.provider.name} g but i'm not sure how add order p.createdon desc , .take(1), per partition/group.
something (appended @ end of query):
select new { g.key, product = g.orderbydescending(x => x.createdon).first() } should job; or perhaps more conveniently:
select new { g.key.productid, g.key.name, product = g.orderbydescending(x => x.createdon).first() } or if don't need key explicitly (because available under item anyway), just:
select g.orderbydescending(x => x.createdon).first() basically, each g igrouping<t> (for anonymous t), means each g has .key property group, , each g is ienumerable<> sequence of original elements (presumably product).
Comments
Post a Comment