-2

Say I have 2 dictionaries:

            var dict1 = new Dictionary<string, int> {
                { "key1", 1 },
                { "key2", 2 },
            };


            var dict2 = new Dictionary<string, int> {
                { "key2", -3 },
                { "key3", -4 },
            };

Is there a simple way to "add" them? The result would be:

            var dict3 = new Dictionary<string, int> {
                { "key1", 1 },
                { "key2", -1 },
                { "key3", -4 },
            };

Keys are merged and values are summed up by key

Bruno
  • 4,685
  • 7
  • 54
  • 105
  • 2
    What have you tried? StackOverflow expects you to make some attempt and provide a [mcve]. Take a look at [ask]. – Herohtar Nov 13 '19 at 18:40
  • @HerohtarI have tried creating an empty `dict3` first and looping through each ones, adding the new entry if not present or updating the value if present, but that code is pretty ugly I feel – Bruno Nov 13 '19 at 18:42

1 Answers1

4

You could do something like this:

var d3 = dict1.Union(dict2)
              .GroupBy(kvp => kvp.Key)
              .ToDictionary(g => g.Key, g => g.Select(x => x.Value).Sum());
germi
  • 4,628
  • 1
  • 21
  • 38