gpt4 book ai didi

LINQ - 使用类型计数对对象进行分组

转载 作者:行者123 更新时间:2023-12-04 06:20:21 24 4
gpt4 key购买 nike

我有一组对象,每个对象都由特定的“组”定义。如何编写 LINQ 查询以生成按“组”分组的每个对象的计数。

例如,假设我有以下类(class);

public class Release 
{
int ReleaseNumber;

public ReleaseDetails[] details;

}

public class ReleaseDetails
{
string Group;

// other details omitted
}

对于给定的版本,我希望能够产生如下输出;
Release number 1 contains the following details;
- 17 records in Group A
- 12 records in Group B
- 6 records in Group C

任何帮助深表感谢。

最佳答案

你可以做类似的事情

var q = from d in r.Details
group d by d.Group into counts
select new { Count = counts.Count(), Group = counts.Key };

完整示例:
        Release r = new Release
{
ReleaseNumber = 1
,
Details = new ReleaseDetails[]
{
new ReleaseDetails { Group = "a"},
new ReleaseDetails { Group = "a"},
new ReleaseDetails { Group = "b"},
new ReleaseDetails { Group = "c"},
new ReleaseDetails { Group = "d"},
new ReleaseDetails { Group = "d"},
new ReleaseDetails { Group = "e"},

}
};

var q = from d in r.Details
group d by d.Group into counts
select new { Count = counts.Count(), Group = counts.Key };

foreach (var count in q)
{
Console.WriteLine("Group {0}: {1}", count.Group, count.Count);
}

关于LINQ - 使用类型计数对对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6660141/

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