gpt4 book ai didi

C# LINQ 每组取有限结果

转载 作者:太空宇宙 更新时间:2023-11-03 20:17:10 24 4
gpt4 key购买 nike

我有一个列表,其中包含名为“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

最佳答案

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

关于C# LINQ 每组取有限结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15997847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com