ByulTaeng
ByulTaeng

Reputation: 1269

GroupBy then Take in LINQ to Entities?

Let's say I have the following items:

ID      Category        Name

1       Fruit           Banana
2       Car             Mescedes
3       Fruit           Blackberry
4       Fruit           Mango
5       Car             Lexus
6       Fruit           Melon
7       Car             BMW
8       Car             Toyota

I want to group them into Category and take only the first 3 items of each Category. Is it possible?

I expected the output:

ID        Category        Name

1        Fruit           Banana
3        Fruit           Blackberry
4        Fruit           Mango
2        Car             Mescedes
5        Car             Lexus
7        Car             BMW

Any helps would be appreciated!

Upvotes: 0

Views: 2527

Answers (2)

Euphoric
Euphoric

Reputation: 12849

From head and not tested:

from c in categoryList
group by c.Category into g
let fewItems = g.Take(3).ToList()
return new { Category = g.Key, Items = fewItems }

Upvotes: 4

sajoshi
sajoshi

Reputation: 2763

Lets say you list collection is named as categoryList..

The linq queries to achive what you want is:

categoryList.GroupBy(c=>c.Category).Take(3)

Upvotes: 0

Related Questions