Domanda

I have SortedList in descending order.

public class MyComparer : IComparer<int>
    {
        public int Compare(int x, int y)
        {
            if (x.CompareTo(y) > 0)
                return -1;
            return 1;
        }
    }
class Program
{
        static void Main(string[] args)
        {
            SortedList<int, bool> myList = new SortedList<int, bool>(new MyComparer());
            myList.Add(10, true);
            bool check = myList[10];//In this place an exception "Can't find key" occurs
        }
}

When SortedList created without my own IComparer the code works fine and no exception occurs.

È stato utile?

Soluzione

The comparer implementation is invalid; it violates the requirement that:

x.CompareTo(x) == 0 

This confuses the sorted-list when it tries to find an exact match for a given key.

Here's a simple fix:

public int Compare(int x, int y)
{  
    return y.CompareTo(x); // Reverses the in-built comparison.
}

But if you would like to solve this more generally, consider creating a ReverseComparer<T>, such as the one provided here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top