Search code examples
c#linqgroup-byentitiestake

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!


Solution

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