I have two Generic Dictionaries.Both have same keys.But values can be different.I want to compare 2nd dictionary with 1st dictionary .If there are differences between values i want to store those values in 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 a best algorithm to do this.I wrote an algorithm but it have lot of loops. I am seeking a short and efficient idea.Also like a solution by using LINQ query expression or LINQ lamda expression. I am using .Net Framework 3.5 with C#. I found some thing about Except() method. But Unfortunately i couldn't understand what is happening on that method. It is great if any one explains the suggested algorithm.
You mentioned that both dictionaries have the same keys, so if this assumption is correct, you don't need anything fancy:
Or am I misunderstanding your problem?
Assuming both dictionaries have the same keys, the simplest way is
EDIT
Note that
a.Except(b)
gives a different result fromb.Except(a)
:If you've already checked that the keys are the same, you can just use:
To explain, this will:
dict2
dict1
and filter out any entries where the two values are the samedict1
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 toToDictionary
, too.)source of the code