Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging 2 dictionaries having duplicate keys with linq

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
like image 456
Chesnokov Yuriy Avatar asked Aug 01 '11 19:08

Chesnokov Yuriy


People also ask

Can dictionaries contain duplicate keys?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can dictionaries have duplicate keys C#?

In Dictionary, the key cannot be null, but value can be. In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements.

What happens if we add duplicate key in dictionary c#?

All of these associate a key with a value and are represented internally by a collection of key/value pairs. However, none of them permit duplicate keys and so, if you try to add an item whose key is already present, an exception is thrown.


1 Answers

d1.Concat(d2.Where( x=> !d1.Keys.Contains(x.Key)));
like image 51
Eric H Avatar answered Oct 12 '22 16:10

Eric H