我有一个使用自定义键结构的排序字典。为了便于排序,我在键中有一些变量,我不想参与相等的比较。
类的一个例子
public struct Key
{
//Needs to participate in equality comparison for SortedDictionary.TryGetValue();
public int intKey;
public object objectKey;
//Needs to be ignored in SortedDictionary.TryGetValue();
public int sortingVariable;
public string otherSortingVariable;
}我尝试过重载Equals和GetHashCode,以至于new Key().equals(new Key())返回true。
但是,SortedDictionary.TryGetValue(new Key(), out Value)返回false
发布于 2016-05-29 18:05:00
您实现的方法不被排序的实现所使用。相反,您需要在IComparable中实现struct接口。
public struct Key : IComparable<Key>
{
public int CompareTo(Key other)
{
return Comparer.Default<string>.Compare(otherSortingVariable, other.otherSortingVariable);
}
}或者实现IComparer接口的自定义类:
public class KeyComparer : Comparer<Key>
{
public override int Compare(Key x, Key y)
{
return Comparer.Default<string>.Compare(x.otherSortingVariable, y.otherSortingVariable);
}
}并将上述类的实例传递给接受自定义比较器的SortedDictionary构造函数过载。
https://stackoverflow.com/questions/37513033
复制相似问题