c# LINQ每组取有限的结果

本文关键字:结果 LINQ | 更新日期: 2023-09-27 18:09:09

我有一个列表,其中包括名为'ID', 'Name'和'Category'的类。列表中有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

c# LINQ每组取有限的结果

使用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个元素