Similarity between Dictionaries

  • Thread starter Thread starter Luigi
  • Start date Start date
L

Luigi

Hi all,
I have two Dictionary exactly the same, but if I try to verify this
likeness, I get false, like this code:

Dictionary<int,string> TestA = new Dictionary<int,string>();
Dictionary<int,string> TestB = new Dictionary<int,string>();

TestA.Add(1, "TestString");
TestB.Add(1, "TestString");

bool result = (TestA == TestB); // returns "false"

How can I check the similarity of 2 dictionaries?
(I'm using C# 2.0)

Thanks in advance.

Luigi
 
Peter Duniho said:
Just for the record, that fails because the Dictionary class doesn't
provide an operator == overload. It also doesn't override
Object.Equals(), so you couldn't use that as a workaround either.

If you had been using C# 3.0 with .NET 3.5, you would have been able to
use the Enumerable.SequenceEqual() extension method:

bool result = TestA.SequenceEqual(TestB);

But if you're stuck with C# 2.0, I think you'll have to essentially
implement the iterative comparison yourself. I'm not aware of a built-in
implementation of something like this for the Dictionary class.

Thanks Pete,
and how can I solve this, with a dictionary<string,decimal?>?

L
 
Luigi expressed precisely :
Thanks Pete,
and how can I solve this, with a dictionary<string,decimal?>?

L

Something like this:
If the sizes of the dictionaries are not equal, then they don't contain
the same items.
If the sizes are equal, loop through all items of dictionaryA, and test
if the key is present in dictionaryB with the same value. When a
mismatch is found, the dictionaries are not equal. When you have tested
all items and didn't find a mismatch, then they are equal.

Hans Kesting
 
Just for the record, that fails because the Dictionary class doesn't  
provide an operator == overload.  It also doesn't override  
Object.Equals(), so you couldn't use that as a workaround either.

If you had been using C# 3.0 with .NET 3.5, you would have been able to  
use the Enumerable.SequenceEqual() extension method:

     bool result = TestA.SequenceEqual(TestB);

This doesn't quite work for Dictionary (and HashSet), because the
order in which elements are enumerated is not defined (not only it may
be different from insertion order, but it also needs not be the same
for two different dictionaries - and I would imagine that some
creative play with Capacity and removing/readding elements can be used
to achieve this effect in practice).
 
Back
Top