I have a collection. I need to group the collection by "A" property. And I have to sort each group by"B" property. Then select first 5 from each group.
Can anyone suggest a LINQ query for this?
The way I tried is not working.
(from item in Recipes
orderby item.Rating descending
group item by item.MainCategory).Take(5)
The query should return IEnumerable<IGrouping<string, myrecipetype>>
You are taking first five groups. Instead you need to select first five items from each group:
from item in Recipes
orderby item.Rating descending
group item by item.MainCategory into g
select g.Take(5)
UPDATE:
from item in Recipes
orderby item.Rating descending
group item by item.MainCategory into g
select g.Take(5).GroupBy(item => item.MainCategory).First()
Edit: In your case, with sorting added (after the OP was updated):
Recipes.GroupBy(recipy => recipy.MainCategory)
.Select(recipyGroup => recipyGroup.OrderBy(recipy => recipy.Rating)
.Take(5))
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