33

Possible Duplicate:
Merging dictionaries in C#

dictionary 1

"a", "1"
"b", "2"

dictionary 2

"c", "3"
"d", "4"

dictionary 3

"e", "5"
"f", "6"

Combined dictionary

"a", "1"
"b", "2"
"c", "3"
"d", "4"
"e", "5"
"f", "6"

How do I combine the above 3 dictionaries into a single combined dictionary?

Community
  • 1
  • 1
dotnet-practitioner
  • 13,968
  • 36
  • 127
  • 200

2 Answers2

152
var d1 = new Dictionary<string, int>();
var d2 = new Dictionary<string, int>();
var d3 = new Dictionary<string, int>();

var result = d1.Union(d2).Union(d3).ToDictionary (k => k.Key, v => v.Value);

EDIT
To ensure no duplicate keys use:

var result = d1.Concat(d2).Concat(d3).GroupBy(d => d.Key)
             .ToDictionary (d => d.Key, d => d.First().Value);
Magnus
  • 45,362
  • 8
  • 80
  • 118
  • 3
    Note that `ToDictionary` will throw exception on duplicates – dtb May 11 '12 at 22:53
  • @dtb there wont be any duplicates when used with `union` as in my answer. – Magnus May 11 '12 at 22:56
  • 26
    @Magnus: `Union` removes duplicates only if both key and value of the KeyValuePair are equal. If you have e.g. `var d1 = new Dictionary() { { "a", 5 } }; var d2 = new Dictionary() { { "a", 6 } };` then you get duplicate keys. – dtb May 12 '12 at 00:30
  • What would the solution be if you had an unknown number of Dictionaries you were trying to merge? Is there a way to take a List of dictionaries and merge them in the same way? thank you – Paul W. May 05 '17 at 23:28
  • 3
    @PaulW. You could do: `dictionaries.SelectMany(x => x).ToDictionary(x => x.Key, x => x.Value)` – Magnus May 08 '17 at 07:04
15

Just loop through them:

var result = new Dictionary<string, string>();

foreach (var dict in dictionariesToCombine) {
    foreach (var item in dict) {
        result.Add(item.Key, item.Value);
    }
}

(Assumes dictionariesToCombine is some IEnumerable of your dictionaries to combine, say, an array.)

Ry-
  • 218,210
  • 55
  • 464
  • 476