Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/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# 将表中的列聚合为列表<;字典<;ColumnT,ValueT>&燃气轮机;_C#_.net_Linq_Aggregation - Fatal编程技术网

C# 将表中的列聚合为列表<;字典<;ColumnT,ValueT>&燃气轮机;

C# 将表中的列聚合为列表<;字典<;ColumnT,ValueT>&燃气轮机;,c#,.net,linq,aggregation,C#,.net,Linq,Aggregation,在一个表中,每一行都是一个字典,LINQ聚合列值的方式是什么 数据表的格式为 2010 | 2011 A 11 | 12 B 21 | 22 这表示为字典列表: var A = new Dictionary<String, int>(); A.Add("2010", 11); A.Add("2011" 12), var B = new Dictionary<String, int>(); A.Add("2010", 21); A.Add("2

在一个表中,每一行都是一个
字典
,LINQ聚合列值的方式是什么

数据表的格式为

   2010 | 2011
A    11 |   12
B    21 |   22
这表示为字典列表:

var A = new Dictionary<String, int>();
A.Add("2010", 11);
A.Add("2011"  12),
var B = new Dictionary<String, int>();
A.Add("2010", 21);
A.Add("2011"  22),
var table = List<Dictionary<String,int>>() { A, B };

我想你的最后一行实际上是:

totalsRow[cell.Key] = AggregationFunc(runningValue, cell.Value);
因为否则,您不会在任何地方使用嵌入字典的整数值


你可以做:

var totalsRow = table.SelectMany(row => row)
                     .GroupBy(kvp => kvp.Key)
                     .ToDictionary(group => group.Key, 
                                   group => group.Sum(kvp => kvp.Value));
如果要保留AggregationFunc,请将
ToDictionary
的第二个参数替换为:

group => group.Aggregate(0, 
         (runningValue, nextKvp) => AggregationFunc(runningValue, nextKvp.Value))

其想法是:

  • 首先,将字典列表展平为键值对序列
  • 按键对键值对进行分组
  • 将键值对组转换为具有以下功能的字典:
    • “密钥”是组的密钥,即组中所有对共享的密钥
    • “值”是组中所有对的单个值的集合
  • 这是:

    var totals = table
        .SelectMany(_ => _)
        .GroupBy(_ => _.Key, _ => _.Value)
        .ToDictionary(
            group => group.Key,
            group => group.Aggregate(AggregationFunc));
    

    精彩的最后一行实际上很好,它从字典中提取一个值(按键索引)。@dbkk:Cheers。它从输出字典中提取一个值是的,但它不使用当前单元格的值。我觉得有点滑稽。
    group => group.Aggregate(0, 
             (runningValue, nextKvp) => AggregationFunc(runningValue, nextKvp.Value))
    
    var totals = table
        .SelectMany(_ => _)
        .GroupBy(_ => _.Key, _ => _.Value)
        .ToDictionary(
            group => group.Key,
            group => group.Aggregate(AggregationFunc));