Bad Dub Bad Dub - 3 months ago 33
C# Question

Linq - Group By Id, Order By and Then select top 5 of each grouping

Is there some way in linq group By Id, Order By descending and then select top 5 of each grouping? Right now I have some code shown below, but I used

and it obviously selects the top 5 regardless of grouping.

Items = list.GroupBy(x => x.Id)
.Select(x => x.OrderByDescending(y => y.Value))
.Select(y => new Home.SubModels.Item {
Name= y.FirstOrDefault().Name,
Value = y.FirstOrDefault().Value,
Id = y.FirstOrDefault().Id


You are almost there. Use Take in the Select statement:

var items = list.GroupBy(x => x.Id)   
                //For each IGrouping - order nested items and take 5 of them           
                .Select(x => x.OrderByDescending(y => y.Value).Take(5))

This will return an IEnumerable<IEnumerable<T>>. If you want it flattened replace Select with SelectMany