Search code examples
c#dictionarysorteddictionary

SortedDictionary.TryGetValue() Overloads


I have a sorted dictionary using custom key structs. In order to facilitate sorting, I have some variable in the key that I dont want to participate in equality comparison.

An example of the class

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;
}

I have tried overloading Equals and GetHashCode to the extent that new Key().equals(new Key()) returns true.

However, SortedDictionary.TryGetValue(new Key(), out Value) returns false


Solution

  • The methods you implemented are not used by sorted implementations. Instead, you need to either implement IComparable<T> interface in your struct:

    public struct Key : IComparable<Key> 
    {
        public int CompareTo(Key other)
        {
            return Comparer.Default<string>.Compare(otherSortingVariable, other.otherSortingVariable);
        }
    }
    

    or a custom class implementing IComparer<T> interface:

    public class KeyComparer : Comparer<Key>
    {
        public override int Compare(Key x, Key y)
        {
            return Comparer.Default<string>.Compare(x.otherSortingVariable, y.otherSortingVariable);
        }
    }
    

    and pass an instance of the above class to the SortedDictionary constructor overload that accepts custom comparer.