0

I have and want to compare two IDictionary collection for sepecific key value. E.g. IDictionary col1 and E.g. IDictionary col2.

i am looping all items from both the collection and finally using this "Equals" to compare key values from both the collection -

if(col1.Values[key2].Equals(col2.Values[key2])) 
{

}

But "Equals" will compare object reference, so it is right way to do or any alternative solution ?

5
  • If Equals compares the reference depends on whether it was overriden in the class. So what type are the values in your dictionaries? Sep 9, 2011 at 9:13
  • The title of this post has nothing to do with the question being asked Sep 9, 2011 at 9:16
  • key is string and value is object.
    – user936405
    Sep 9, 2011 at 9:21
  • If value is and object do Col1 and Col2 always contains the same underlying type e.g. are you sure you are never comparing a string with an int. Sep 9, 2011 at 9:31
  • since value is object, for same key in both the collection, value would be of same type (string or int or any thing).
    – user936405
    Sep 9, 2011 at 9:36

1 Answer 1

1

There are a couple of things you can do:

  1. override Equals (and GetHashCode) on the type that represents your values
  2. don't compare using equals but your own function
  3. implement a comparer and use this and a couple more

In this case I would use 2) if you don't need to compare those values elsewhere if you do than use 1

Remarks to 1:)

you will need on your ValueType (MyValue):

class MyValue
{
   // ...
   public override GetHashCode()
   {
      return this.Property1.GetHashCode();
      // if you want to compare more properties hash them all and use some function (for example ^)
      // to "add" the values
   }

   public override Equals(obj o)
   {
      if (ReferenceEquals(null, o)) return false;
      if (ReferenceEquals(this, o)) return true;
      if (o.GetType() != typeof (MyValue)) return false;
      var v2 = o as MyValue;
      return Equals(v2.Property1, this.Property1);
      // if you want to compare more than one property use && and Equals on them all
   }
}

Remarks to 2:) instead of

if(col1.Values[key2].Equals(col2.Values[key2])) 

use some thing like this

bool CompareTwoValues(MyValue v1, MyValue v2)
{
   if(!Equals(v1.Property1, v2.Property1)) return false;
   // ... whatever you have to compare based on the values
   return true;
}

with

if (CompareTwoValues(col1.Values[key2], col2.Values[key2])
{
  // ....
}

PS: Equals and GetHashCode can be (very) tricke sometimes - please search a bit an make sure that GetHashCode is implemented correctly. Also better only compare immutable values on your classes this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.