How to sort the generic SortedList in the descending order?


You have learned about SortedList<TKey, TValue> in the C# tutorials section. The SortedList<TKey, TValue> stores the key-value pairs in the ascending order of key, by default. Here, you will learn how to create SortedList<TKey, TValue> that stores elements in descending order.

SortedList<TKey, TValue> uses the IComparer<T> instance to compare the keys and sort the collection. So, in order to sort the collection in descending order, we need to create a custom class that compares values in descending order.

Example: SortedList with IComparer
class DecendingComparer<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 DecendingComparer<int>());
        descSortedList.Add(1, 1);
        descSortedList.Add(4, 4);
        descSortedList.Add(3, 3);
        descSortedList.Add(2, 2);

        for (int i = 0; i < descSortedList.Count; i++)
        {
            Console.WriteLine("key: {0}, value: {1}", descSortedList.Keys[i], descSortedList.Values[i]);
        }
}

Use Comparer<T> to sort the SortedList in descending order instead of creating a separate class.

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

        for (int i = 0; i < descSortedList.Count; i++)
        {
            Console.WriteLine("key: {0}, value: {1}", descSortedList.Keys[i], descSortedList.Values[i]);
        }
}

Thus, you can create an instance of SortedList<TKey, TValue> to sort the collection in descending order.