0

我想合并任意数量的 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);

我必须自己编写扩展方法还是已经存在类似的方法?

4

2 回答 2

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));
于 2013-08-24T19:55:36.063 回答
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);
于 2013-08-24T19:49:53.050 回答