2013-08-24 9 views
0

我想合并任意数量的Dictionary实例,如果某个键出现多次,我想执行一个操作,例如, currentResultValue += newFoundValue合并n字典实例并对重复密钥执行操作

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

示例输入:

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
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
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); 
+0

你试过吗? d是IDictionary类型,不提供'd.Key'属性。 –

+0

@ D.R。不是,但只是编辑。 –

+0

我对编辑可以,但是,I4V的答案似乎有点简单,这就是为什么我要接受他的答案。 Upvote虽然你的努力。 –