Sorting a SortedList in Descending Order in C#

By FoxLearn 2/7/2025 3:55:07 AM   53
In C#, the SortedList<TKey, TValue> class stores key-value pairs in ascending order of the key by default. If you need to store the elements in descending order, you can achieve this by using a custom comparer.

The SortedList<TKey, TValue> relies on the IComparer<T> interface to compare keys and determine their order. To sort the collection in descending order, we need to implement a custom comparer.

Using a Custom Class for Comparison

Here’s an example using a custom comparer class that sorts the keys in descending order:

class DescendingComparer<TKey> : IComparer<int>
{
    public int Compare(int x, int y)
    {
        return y.CompareTo(x);
    }
}

class Program
{
    static void Main(string[] args)
    {
        SortedList<int, int> descSortedList = new SortedList<int, int>(new DescendingComparer<int>());
        descSortedList.Add(1, 1);
        descSortedList.Add(4, 4);
        descSortedList.Add(3, 3);
        descSortedList.Add(2, 2);

        foreach (var item in descSortedList)
        {
            Console.WriteLine("key: {0}, value: {1}", item.Key, item.Value);
        }
    }
}

In this example, we created a custom comparer DescendingComparer<TKey> that compares values in reverse order (y.CompareTo(x)). We then pass this comparer to the SortedList constructor to sort the keys in descending order.

Using Comparer<T> to Sort Without a Custom Class

Instead of creating a separate class, you can use the Comparer<T> class directly to achieve the same result.

class Program
{
    static void Main(string[] args)
    {
        var descendingComparer = Comparer<int>.Create((x, y) => y.CompareTo(x));
        
        SortedList<int, int> descSortedList = new SortedList<int, int>(descendingComparer);
        descSortedList.Add(1, 1);
        descSortedList.Add(4, 4);
        descSortedList.Add(3, 3);
        descSortedList.Add(2, 2);

        foreach (var item in descSortedList)
        {
            Console.WriteLine("key: {0}, value: {1}", item.Key, item.Value);
        }
    }
}

Here, we use Comparer<int>.Create to define the comparison logic, where the second parameter (y.CompareTo(x)) ensures the keys are sorted in descending order.

Using either of these methods, you can create a SortedList<TKey, TValue> that sorts its elements in descending order.