Saturday, 24 August 2013

Merging n Dictionary instances & execute action on duplicate keys

Merging n Dictionary instances & execute action on duplicate keys

I want to merge an arbitrary amount of Dictionary instances, if a key
occurs multiple times I want to execute an action, e.g. currentResultValue
+= newFoundValue.
Sample context: Map/Reduce pattern, reduce step, I counted the occurences
of words in a really big text and had 10 mappings, each returning a
Dictionary<string, int>. In the reduce call I now want to merge all those
dictionaries into one.
Example input:
Dictionary 1:
"key1" -> 5
"key2" -> 3
Dictionary 2:
"key2" -> 1
Dictionary 3:
"key1" -> 2
"key3" -> 17
Expected result:
"key1" -> 7
"key2" -> 4
"key3" -> 17
I'd prefer a LINQ-based solution, e.g. something like:
IEnumerable<IDictionary<string, int>> myDictionaries = ...;
myDictionaries.Reduce((curValue, newValue) => curValue + newValue);
Do I have to write my extension method myself or is something like that
already existing?

No comments:

Post a Comment