合并n个字典实例&对重复键执行操作

时间:2013-08-24 19:46:44

标签: c# .net linq

我想合并任意数量的Dictionary实例,如果一个键出现多次,我想执行一个动作,例如currentResultValue += newFoundValue

示例上下文:Map / Reduce模式,reduce步骤,我计算了一个非常大的文本中出现的单词,并有10个映射,每个映射都返回Dictionary<string, int>。在reduce调用中,我现在想将所有这些字典合并为一个。

示例输入:

Dictionary 1:
    "key1" -> 5
    "key2" -> 3

Dictionary 2:
    "key2" -> 1

Dictionary 3:
    "key1" -> 2
    "key3" -> 17

预期结果:

"key1" -> 7
"key2" -> 4
"key3" -> 17

我更喜欢基于LINQ的解决方案,例如类似的东西:

IEnumerable<IDictionary<string, int>> myDictionaries = ...;
myDictionaries.Reduce((curValue, newValue) => curValue + newValue);

我是否必须自己编写扩展方法,或者是否已经存在?

2 个答案:

答案 0 :(得分:2)

var d1 = new Dictionary<string, int>() { { "key1", 5 }, { "key2", 3 } };
var d2 = new Dictionary<string, int>() { { "key2", 1 } };
var d3 = new Dictionary<string, int>() { { "key1", 2 }, { "key3", 17 } };


var dict = new[] { d1, d2, d3 }.SelectMany(x => x)
                    .GroupBy(x => x.Key)
                    .ToDictionary(x => x.Key, x => x.Sum(y => y.Value));

答案 1 :(得分:1)

var result = myDictionaries.SelectMany(x=>x)
                           .GroupBy(d=>d.Key)
                           .Select(g=> new KeyValuePair<string,int>(g.Key, g.Sum(x=>x.Value)))
                           .ToDictionary(k=>k.Key,v=>v.Value);