Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two Dictionaries in C#

I have two generic Dictionaries. Both have the same keys, but their values can be different. I want to compare the 2nd dictionary with the 1st dictionary. If there are differences between their values, I want to store those values in a separate dictionary.

1st Dictionary ------------ key       Value  Barcode   1234566666 Price     20.00   2nd Dictionary -------------- key       Value  Barcode   1234566666 Price     40.00   3rd Dictionary -------------- key       Value  Price     40 

Can anyone give me the best algorithm to do this? I wrote an algorithm but it has a lot of loops. I am seeking a short and efficient idea, like a solution using LINQ query expressions or LINQ lambda expressions. I am using .NET Framework 3.5 with C#. I found something about the Except() method, but unfortunately I couldn't understand what is happening on that method. It would be great if anyone could explain the suggested algorithm.

like image 710
Thabo Avatar asked Mar 03 '12 15:03

Thabo


People also ask

Can two dictionaries be compared?

For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.

Can we compare two dictionaries in C#?

No... actually keys must be same in name and count.

How do you compare keys in two dictionaries?

The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

How do I check if two dictionaries are equal in C#?

Equals(Object) Method which is inherited from the Object class is used to check if a specified Dictionary object is equal to another Dictionary object or not. Syntax: public virtual bool Equals (object obj); Here, obj is the object which is to be compared with the current object.


1 Answers

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 in dict2.

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.)

like image 160
Jon Skeet Avatar answered Oct 05 '22 21:10

Jon Skeet