Sorting a SortedList in Descending Order in C#
By FoxLearn 2/7/2025 3:55:07 AM 103
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 C
omparer<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.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#