Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...