C#LINQ每个分组的结果有限

时间:2013-04-14 10:03:51

标签: c# linq list

我的列表包含名为“ID”,“名称”和“类别”的类。列表中有6个项目。

List<MyData> list = 
{
    {0, "John", "Police"}, 
    {1,"Michael", "Police"},
    {2,"Alice", "Police"}, 
    {3, "Ferdinand", "Thief"}, 
    {4, "Jocas", "Thief"}, 
    {5, "Connor", "Thief"}
};

我想用LINQ的“类别”列出每组数量有限的数据。

示例:我想要每个'Cateogory'的列表2项。列出的应该是:

John Police

Michael Police

Ferdinand Thief

Jocas Thief

1 个答案:

答案 0 :(得分:5)

使用TakeSelectMany的组合:

var results = list.GroupBy(x => x.Category).SelectMany(g => g.Take(2)).ToList();

我在以下Item课程中测试了它:

public class Item
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
}

并查询:

List<Item> list = new List<Item>
{
    new Item { ID = 0, Name = "John", Category = "Police"}, 
    new Item { ID = 1, Name = "Michael", Category = "Police"},
    new Item { ID = 2, Name = "Alice", Category = "Police"}, 
    new Item { ID = 3, Name = "Ferdinand", Category = "Thief"}, 
    new Item { ID = 4, Name = "Jocas", Category = "Thief"}, 
    new Item { ID = 5, Name = "Connor", Category = "Thief"}
};

var results = list.GroupBy(x => x.Category).SelectMany(g => g.Take(2)).ToList();

根据需要返回4个元素。