Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用linq求和值的步骤_C#_Linq - Fatal编程技术网

C# 使用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

在下面的代码中,我有一个列表,我正在尝试使用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

              .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)});