Reputation: 15934
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.
Upvotes: 0
Views: 940
Reputation: 73482
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
Upvotes: 1