1

我的列表包括名为“ID”、“名称”和“类别”的类。列表中有 6 项。

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

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

示例:我想为每个“类别”列出 2 个项目。列出应如下:

John Police

Michael Police

Ferdinand Thief

Jocas Thief
4

1 回答 1

5

使用Take和的组合SelectMany

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 个元素。

于 2013-04-14T10:07:12.510 回答