.NET
Dictionary
Reverse Sorting
Data Structures
C#

Reverse Sorted Dictionary in .NET

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

A plain Dictionary<TKey, TValue> in .NET is not a sorted container at all, so you cannot make it “reverse sorted” in place. If you need keys kept in descending order, the usual solution is SortedDictionary<TKey, TValue> or SortedList<TKey, TValue> with a custom comparer that reverses the normal ordering.

Why Dictionary Is the Wrong Starting Point

Dictionary<TKey, TValue> is optimized for key lookup by hash, not for ordered traversal. Enumeration order is not the defining feature of the type, so “reverse sorted dictionary” usually really means one of two things:

  • keep items ordered by key in descending order
  • produce a one-time descending view during enumeration

Those are different needs and should not be solved with the same tool automatically.

Use SortedDictionary with a Reverse Comparer

If you want the collection itself to maintain descending key order, provide a comparer that reverses the default comparison.

csharp
1using System;
2using System.Collections.Generic;
3
4public sealed class DescendingComparer<T> : IComparer<T> where T : IComparable<T>
5{
6    public int Compare(T? x, T? y)
7    {
8        if (ReferenceEquals(x, y)) return 0;
9        if (x is null) return 1;
10        if (y is null) return -1;
11        return y.CompareTo(x);
12    }
13}
14
15var dict = new SortedDictionary<int, string>(new DescendingComparer<int>())
16{
17    [10] = "ten",
18    [2] = "two",
19    [7] = "seven"
20};
21
22foreach (var pair in dict)
23{
24    Console.WriteLine($"{pair.Key} -> {pair.Value}");
25}

This iterates in descending key order because the comparer defines that order.

SortedList Is Also an Option

SortedList<TKey, TValue> can use the same reverse comparer:

csharp
1var list = new SortedList<int, string>(new DescendingComparer<int>())
2{
3    [10] = "ten",
4    [2] = "two",
5    [7] = "seven"
6};

Both types maintain sorted keys, but they differ internally and therefore differ in performance characteristics. In general terms:

  • 'SortedDictionary is tree-based'
  • 'SortedList is array-based'

That means SortedList can be very efficient for indexed access and small collections, while SortedDictionary tends to handle insert-heavy usage more gracefully.

If You Only Need a Reverse View Once

Sometimes you do not need a permanently sorted container at all. You just want a descending enumeration of an existing dictionary.

csharp
1using System.Linq;
2
3var dict = new Dictionary<int, string>
4{
5    [10] = "ten",
6    [2] = "two",
7    [7] = "seven"
8};
9
10var reversed = dict.OrderByDescending(pair => pair.Key);
11
12foreach (var pair in reversed)
13{
14    Console.WriteLine($"{pair.Key} -> {pair.Value}");
15}

This is often the simplest solution when the data structure itself does not need to maintain order between mutations.

Choose Based on the Actual Requirement

Use a permanently sorted structure when:

  • inserts and reads should always reflect descending order
  • multiple consumers depend on ordered enumeration
  • you want the order maintained automatically after each change

Use one-time sorting when:

  • storage is naturally unordered
  • you only need sorted output at presentation time
  • lookup speed matters more than maintained order

The mistake is reaching for a sorted structure when you only needed sorted output once.

Comparer Design Details

The comparer must define a total ordering. For descending order, reversing CompareTo is the normal approach, but do not accidentally return inconsistent results. Broken comparers can make sorted collections behave unpredictably.

If the key type already has a custom comparer, reverse that comparer rather than reinventing the ordering logic from scratch.

Common Pitfalls

  • Assuming Dictionary<TKey, TValue> itself can be turned into a reliably reverse-sorted container just by changing how you enumerate it.
  • Using a sorted collection when a one-time OrderByDescending would have been simpler and cheaper.
  • Writing an inconsistent custom comparer, which can break insertion and lookup behavior in sorted collections.
  • Choosing between SortedDictionary and SortedList without considering whether the workload is more read-heavy or insert-heavy.
  • Forgetting that “reverse sorted by key” and “reverse sorted by value” are different problems with different implementations.

Summary

  • A normal .NET Dictionary<TKey, TValue> is not a sorted collection.
  • For persistent descending key order, use SortedDictionary<TKey, TValue> or SortedList<TKey, TValue> with a reverse comparer.
  • For one-time display ordering, use OrderByDescending during enumeration instead.
  • The right data structure depends on whether you need maintained order or just sorted output.
  • A correct comparer is central to any reverse-sorted dictionary design.

Course illustration
Course illustration

All Rights Reserved.