Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple dictionaries with same key in them into one dictionary with the sum of values

Tags:

c#

dictionary

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 :

  1. Create a Final empty dictionary.
  2. Loop over the list of dictionaries.
  3. Loop over the KeyValue pair.
  4. Check if the key exists in final dictionary. If yes then add the value from KeyValue pair to final dictionary. If not then add to dictionary the KeyValue pair

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

like image 865
StackOverflowVeryHelpful Avatar asked Aug 21 '15 08:08

StackOverflowVeryHelpful


People also ask

How do you combine two dictionary values for common keys?

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.


1 Answers

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));
like image 194
Eser Avatar answered Oct 17 '22 06:10

Eser