INPUT
Dictionary 1
"a", "1"
"b", "2"
Dictionary 2
"a", "3"
"b", "4"
Dictionary 3
"a", "5"
"b", "6"
OUTPUT (Concatenation of the dictionaries above)
Final dictionary
"a", "9"
"b", "12"
I wrote a pseudo code for this :
Since this requires two foreach loops is there a lync version in c# for this and also which doesn't throw any exception.
Some of the questions that i referred on stackoverflow was Combine multiple dictionaries into a single dictionary
Using Counter The Counter function from the Collections module can be directly applied to merge the two dictionaries which preserves the keys. And in turn adds the values at the matching keys.
var dict1 = new Dictionary<string, int>() { { "a", 1 }, { "b", 2 } };
var dict2 = new Dictionary<string, int>() { { "a", 3 }, { "b", 4 } };
var dict3 = new Dictionary<string, int>() { { "a", 5 }, { "b", 6 } };
var resDict = dict1.Concat(dict2)
.Concat(dict3)
.GroupBy(x => x.Key)
.ToDictionary(x => x.Key, x => x.Sum(y=>y.Value));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With