How to compare two Dictionaries in C#
If you've already checked that the keys are the same, you can just use:
var dict3 = dict2.Where(entry => dict1[entry.Key] != entry.Value)
.ToDictionary(entry => entry.Key, entry => entry.Value);
To explain, this will:
- Iterate over the key/value pairs in
dict2
- For each entry, look up the value in
dict1
and filter out any entries where the two values are the same - Form a dictionary from the remaining entries (i.e. the ones where the
dict1
value is different) by taking the key and value from each pair just as they appear indict2
.
Note that this avoids relying on the equality of KeyValuePair<TKey, TValue>
- it might be okay to rely on that, but personally I find this clearer. (It will also work when you're using a custom equality comparer for the dictionary keys - although you'd need to pass that to ToDictionary
, too.)
try :
dictionary1.OrderBy(kvp => kvp.Key)
.SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key))
to check any difference,
dic1.Count == dic2.Count && !dic1.Except(dic2).Any();
following code return all the different values
dic1.Except(dic2)