C# 使用linq求和值的步骤
在下面的代码中,我有一个列表,我正在尝试使用linq查询从列表中获取值并求和这些值。但我不知道如何求和这些值。因此,请帮助我解决此问题C# 使用linq求和值的步骤,c#,linq,C#,Linq,在下面的代码中,我有一个列表,我正在尝试使用linq查询从列表中获取值并求和这些值。但我不知道如何求和这些值。因此,请帮助我解决此问题 list contains: Desc Month level value M1 Jan L1 2 M1 Jan L2 6 M2 Feb L1 4 M2 Feb L2 1 My Expected Result: M1 Jan 8 M2 Feb 5 var sums1 = objList
list contains:
Desc Month level value
M1 Jan L1 2
M1 Jan L2 6
M2 Feb L1 4
M2 Feb L2 1
My Expected Result:
M1 Jan 8
M2 Feb 5
var sums1 = objList
.GroupBy(y => new { y.Desc, y.Month, y.value })
.Select(group => new { KeyValue = group.Key, Count = group.Count() });
将您的
组替换为组。计数
为组。求和(x=>x.value)
将您的组替换为组。计数
为组。求和(x=>x.value)
您不应该将值
包含在分组中-您只想按说明
和月份
进行分组(我假设),然后将值部分相加。两种选择:
var sums1 = objList
.GroupBy(y => new { y.Desc, y.Month })
.Select(group => new { KeyValue = group.Key, Sum = group.Sum(y => y.value) });
或在一次通话中:
var sums1 = objList.GroupBy(
y => new { y.Desc, y.Month },
(key, values) => new { key.Desc, key.Month, Sum = values.Sum(y => y.value) });
您不应该在分组中包含值
——您只需要按Desc
和月
(我假设)进行分组,然后对值部分求和。两种选择:
var sums1 = objList
.GroupBy(y => new { y.Desc, y.Month })
.Select(group => new { KeyValue = group.Key, Sum = group.Sum(y => y.value) });
或在一次通话中:
var sums1 = objList.GroupBy(
y => new { y.Desc, y.Month },
(key, values) => new { key.Desc, key.Month, Sum = values.Sum(y => y.value) });
对IEnumerable使用LINQ的扩展方法
.Select(group => new { KeyValue = group.Key, Sum = group.Sum(obj => obj.value)});
对IEnumerable使用LINQ的扩展方法
.Select(group => new { KeyValue = group.Key, Sum = group.Sum(obj => obj.value)});