Group the collection and make the first 5 of each group

I have a collection. I need to group a collection using property “A”. And I have to sort each group by property "B". Then select 5 first from each group.

Can anyone suggest a LINQ query for this?

The way I tried does not work.

 (from item in Recipes
 orderby item.Rating descending
 group item by item.MainCategory).Take(5)

Request must return IEnumerable<IGrouping<string, myrecipetype>>

+4
source share
2 answers

You accept the first five groups. Instead, you need to select the first five elements 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()
+5
source

Edit: in your case with the addition of sorting (after updating the OP):

Recipes.GroupBy(recipy => recipy.MainCategory)
       .Select(recipyGroup => recipyGroup.OrderBy(recipy => recipy.Rating)
                                         .Take(5))
+1
source

All Articles