Sorting a Generic SortedList in Descending Order in C#

Category > CSHARP || Published on : Wednesday, March 15, 2023 || Views: 255 || C# SortedList Sorting Descending Order Reverse Keys Values


The SortedList class in C# provides a sorted collection of key-value pairs. By default, it sorts the elements in ascending order. However, there are cases where sorting in descending order is required. In this article, we will discuss how to sort a generic SortedList in descending order using C#.

When working with SortedList in C#, it's often necessary to sort the list in descending order. In this article, we'll discuss how to sort a generic SortedList in descending order using C#.

The SortedList class in C# is a collection that represents a sorted list of key-value pairs. It maintains the elements in a sorted order based on the keys. By default, it sorts the elements in ascending order. However, there are cases where sorting in descending order is required.

To sort a SortedList in descending order, we need to first reverse the order of the keys and values in the list. This can be done using the Reverse method of the List class, which can be applied to both the keys and values.

Let's take a look at the following example code that demonstrates how to sort a generic SortedList in descending order:

SortedList<int, string> sortedList = new SortedList<int, string>();
sortedList.Add(3, "Third");
sortedList.Add(1, "First");
sortedList.Add(2, "Second");

// Reverse the order of keys and values
List<int> reversedKeys = sortedList.Keys.Reverse().ToList();
List<string> reversedValues = sortedList.Values.Reverse().ToList();

// Create a new SortedList with reversed keys and values
SortedList<int, string> descendingSortedList = new SortedList<int, string>();
for (int i = 0; i < reversedKeys.Count; i++)
{
    descendingSortedList.Add(reversedKeys[i], reversedValues[i]);
}

// Output the sorted list
foreach (KeyValuePair<int, string> pair in descendingSortedList)
{
    Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}

 

In this code, we first create a generic SortedList of integer keys and string values. We then add three items to the list in random order.

Next, we use the Reverse method of the Keys and Values properties of the sortedList to create two new lists with the keys and values in reverse order. We then create a new SortedList and add the reversed keys and values to it.

Finally, we output the sorted list using a foreach loop.

In conclusion, sorting a generic SortedList in descending order in C# involves reversing the order of the keys and values and adding them to a new SortedList. By using the Reverse method of the List class, we can easily achieve this.