Search code examples
c#linqcollectionsdictionarycomparison

Comparing two Dictionaries in C#


I have two dictionaries, both with the same structure and order (one is supposed to be an exact replicate of the other): Dictionary<int, ICustomInterface>and I want to check that they are equal using SequenceEqual<>

First, I turn the first dictionary into XML, and then read it back to recreate the second one. Upon initial inspection, they are both the same. The ICustomeInterface objects each override the Equals method properly. To check this, I iterate over the elements of the two dictionaries and compare them. They are all equal.

But when I call the SequenceEqual:dictionary1.SequenceEqual(dictionary2); it returns false and the Equals methods of the ICustomInterface objects never get called and it always returns false. However, if I do this:

for (i = 0; i < firstDictionary.Count; i++)
   firstDictionary[i].SequenceEqual(otherSub.ItemSequence[i]);

everything works as expected and it returns true for every line. So, what's going on when I simply call SequnceEqual on the dictionary itself?


Solution

  • "What's going on" is it's comparing KeyValuePair entries for the two dictionaries, in order. Dictionaries are inherently unordered - you shouldn't be relying on anything about the order in which entries come out of them. If you use:

    firstDictionary.OrderBy(pair => pair.Key)
                   .SequenceEqual(secondDictionary.OrderBy(pair => pair.Key))
    

    I suspect you'll find that matches. It's a pretty unpleasant way to compare them though :)