Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group a collection and take first 5 from each group

Tags:

c#

linq

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>>

like image 939
Jawahar Avatar asked Dec 10 '13 13:12

Jawahar


2 Answers

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()
like image 67
Sergey Berezovskiy Avatar answered Nov 15 '22 04:11

Sergey Berezovskiy


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))
like image 24
Kjartan Avatar answered Nov 15 '22 05:11

Kjartan