sunny
sunny

Reputation: 2729

Retrieve n items from each group in linq

I search more on this site for "get 4 top item from each group", but there are many topic about get first item from each group like this

var rr = db.Products
           .GroupBy(x => x.ProductSubTypeCategoryId, (key, g) => g.OrderBy(e => e.PersianName)
           .Take(4).ToList());

or

var rr = db.Products
           .GroupBy(x => x.ProductSubTypeCategoryId).Select(g => new { pname = g.Key, count = g.Count() });

but return only first item from each group. How can I change the code to get 4 items from each group?

Upvotes: 1

Views: 2131

Answers (2)

mm8
mm8

Reputation: 169160

Try this:

var rr = db.Products.GroupBy(x => x.ProductSubTypeCategoryId).Select(g => new { GroupName = g.Key, Items = g.Take(4).ToList() });

This should give you an anonymous object with a GroupName property that returns the ProductSubTypeCategoryId and an Items property that returns a list of up to 4 items for each group.

Upvotes: 4

Roman Marusyk
Roman Marusyk

Reputation: 24569

Try something like this with SelectMany()

var rr = db.Products
       .GroupBy(x => x.ProductSubTypeCategoryId)
       .SelectMany(g => g.OrderBy(e => e.PersianName).Take(4))
       .ToList();

Upvotes: 2

Related Questions