Combine two Dictionaries with LINQ
.net, c#, dictionary, linq
Solution
When you use `Except` by default it uses the default equality comparer, which for the `KeyValuePair` type compares both the keys and the values. You could this approach instead:
var d3 = d1.Concat(d2.Where(kvp => !d1.ContainsKey(kvp.Key)));
Problem
My question has been flagged as a possible duplicate of this question: How to combine two dictionaries without looping? I believe my question is different because I am asking how to combine two dictionaries in a particular way: I want all items from Dictionary1 plus all items from Dictionary2 that are not in (ie the key does not exist) in Dictionary1. I have two dictionaries like this: ``` var d1 = new Dictionary<string,object>(); var d2 = new Dictionary<string,object>(); d1["a"] = 1; d1["b"] = 2; d1["c"] = 3; d2["a"] = 11; d2["e"] = 12; d2["c"] = 13; ``` I would like to combine them into a new Dictionary (technically, it does not have to be a dictionary, it could just be a sequence of `KeyValuePairs`) such that the output contains all of the `KeyValuePairs` from d1 and only the KeyValuePairs from `d2` whose Key does not appear in `d1`. Conceptually: ``` var d3 = d1.Concat(d2.Except(d1)) ``` But that is giving me all of the elements from d1 and d2. Seems like it should be obvious, but I must be missing something.