然后GroupBy接受LINQ to Entities?

时间:2011-03-24 07:50:29

标签: c# linq group-by entities take

假设我有以下项目:

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

我想将它们分组到Category,并且只采用每个Category的前3项。有可能吗?

我期待输出:

ID        Category        Name

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

任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:4)

从头开始,未经测试:

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

答案 1 :(得分:0)

让我们说列表集合被命名为categoryList ..

linq查询到你想要的是:

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