0

I have:

Dictionary<int, MyClass> ItemList = new Dictionary<int, MyClass>();

Where MyClass is something like:

public class MyClass
{
    public int BaseItemID;
    public string Description;


    public MyClass()
    {
    }

    public class Comparer : IEqualityComparer<MyClass>
    {
        public bool Equals(MyClass x, MyClass y)
        {
            if (ReferenceEquals(x, y))
                return true;
            else if (x == null || y == null)
                return false;
            return x.BaseItemID == y.BaseItemID;
        }

        public int GetHashCode(MyClass obj)
        {
            unchecked
            {
                int hash = 17;
                hash = hash * 23 + obj.BaseItemID.GetHashCode();
                return hash;
            }
        }
    }
}

I need to pass this comparer to the the contains on the dictionary but am struggling. I see the dictionary takes something implementing IEqualityComparer in the constructor but:

Dictionary<int, MyClass> ItemList = new Dictionary<int, MyClass>(new MyClass.Comparer());

doesn't seem to work and raises an error on compile time.

I assume I need to implement some KeyValuePair types somewhere but I'm not sure where.

If I was doing this on a normal List<MyClass> then List.Contains(Obj, new MyClass.Comparer()) would work but not in this case.

webnoob
  • 15,747
  • 13
  • 83
  • 165
  • 3
    The dictionary uses the comparer to compare **keys**. Which means that in case of `Dictionary`, `int`s are compared, not your instances. You could pass your own `MyClass` comparer if `MyClass` was a dictionary key. – Patryk Ćwiek Jul 12 '13 at 08:02
  • That actually makes a lot of sense now you mention it. Key is unique anyway .. come to think of it why would I want to compare the value. Sigh. I need more sleep. – webnoob Jul 12 '13 at 08:17

1 Answers1

1

If am not mistaken Dictionary contructor overload requires IEqualityComparer

public Dictionary(IEqualityComparer<TKey> comparer);

in your code you pass "IEqualityComparer of TValue", you can compare only with keys in dictionary not with values

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189