Merging 2 dictionaries having duplicate keys with linq

Viewed 22005

How to merge 2 dictionaries of IDictionary<Guid, MyObject> where MyObject is a class instance?

IDictionary<Guid, MyObject> d1 = new Dictionary<Guid, MyObject>();
d1.Add(guid1, m1);
d1.Add(guid2, m2);
d1.Add(guid3, m3);
IDictionary<Guid, MyObject> d2 = new Dictionary<Guid, MyObject>();
d2.Add(guid2, m2);
d2.Add(guid3, m3);
d2.Add(guid4, m4);
IDictionary<Guid, MyObject> d3 = d1.Union(d2) ???

That in d3 there are the following entries:

guid1,m1
guid2,m2
guid3,m3
guid4,m4
7 Answers

If you have duplicate key then you'll have to handle duplicate key with the using of where clause.

var result = d1.Union(d2.Where(k => !d1.ContainsKey(k.Key))).ToDictionary(k => k.Key, v => v.Value)

Note : It will not get duplicate key. if there will be any duplicate key than it will get d1's key.

This will merge unique keys and unique list of values:

d1.Union(d2).GroupBy(g => g.Key).ToDictionary(pair => pair.Key, pair => pair.First().Value.Union(pair.Last().Value).ToList());
Related