Custom Class used as key in Dictionary but key not found

怎甘沉沦 提交于 2019-11-29 09:55:35
Greg Beech

How are you constructing the dictionary? Are you passing your custom equality comparer in to its constructor?

You have not overridden Equals and GetHashCode. You have implemented a second class which can serve as an EqualityComparer. If you don't construct the Dictionary with the EqualityComparer, it will not be used.

The simplest fix would be to override GetHashCode and Equals directly rather than implementing a comparer (comparers are generally only interesting when you need to supply multiple different comparison types (case sensitive and case insensitive for example) or when you need to be able to perform comparisons on a class which you don't control.

I had this problem, turns out the dictionary was comparing referances for my key, not the values in the object.

I was using a custom Point class as keys. I overrode the ToString() and the GetHashCode() methods and viola, key lookup worked fine.

It looks like you're comparing two strings. Iirc, when using .Equals(), you are comparing the reference of the strings, not the actual contents. To implement an EqualityComparer that works with strings, you would want to use the String.Compare() method.

public class EqualityComparer : IEqualityComparer<ValuesAandB>
{
     public bool Equals(ValuesAandB x, ValuesAandB y)
     {
          return ((String.Compare(x.valueA,y.valueA) == 0) &&
            (String.Compare(x.valueB, y.valueB) == 0));
     }
     // gethashcode stuff here
}

I could be a little off with the code, that should get you close...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!