gpt4 book ai didi

c# - 如何在 Linq 中获得 SUM?

转载 作者:可可西里 更新时间:2023-11-01 08:03:30 28 4
gpt4 key购买 nike

我需要执行以下操作,我有一个 List,其中包含一个包含 2 个整数 id 和 count 的类

现在我想执行以下 linq 查询:

get the sum of the count for each id

但是可以有相同id的items,所以应该加起来,例如:

id=1, count=12
id=2, count=1
id=1, count=2

应该是:

id=1 -> sum 14
id=2 -> sum 1

如何做到这一点?

最佳答案

Group Id 然后是 sum 的项目每组中的 Count:

var result = items.GroupBy(x => x.Id)
.Select(g => new { Id = g.Key, Sum = g.Sum(x => x.Count) });

关于c# - 如何在 Linq 中获得 SUM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16250991/

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