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.
Edit: If you sure all keys are same you can do:
In recent C# versions you can try
I am not sure that
SelectMany
is always the fastest solution, but it is one way to only select the relevant items and generate the resulting entries in the same step. Sadly C# does not supportyield return
in lambdas and while I could have constructed single or no item collections, I choose to use an inner function.Oh and as you say that the keys are the same, it may be possible to order them. Then you could use
Zip
Personally I would tend not to use Linq, but a simple
foreach
like carlosfigueira and vanfosson:to check any difference,
following code return all the different values
try :
You should be able to join them on their keys and select both values. Then you can filter based on whether the values are the same or different. Finally, you can convert the collection to a dictionary with the keys and second values.
Using a loop shouldn't be too bad either. I suspect that they would have similar performance characteristics.