How to sort a dictionary in C#

By FoxLearn 3/5/2025 3:22:55 AM   41
Dictionaries in C# are unordered collections where key-value pairs are not stored in any particular order. Sometimes, you might want to sort the dictionary by either its keys or values.

You can achieve this by using two primary approaches:

  1. Use OrderBy() to sort the dictionary by key or value.
  2. Use a SortedDictionary for an automatically sorted dictionary by key.

For example:

var dictionary = new Dictionary<string, int>()
{
    ["orange"] = 15,
    ["apple"] = 5,
    ["banana"] = 12
};

1. Sort Dictionary with OrderBy()

You can use OrderBy() (from System.Linq) to sort the dictionary either by key or by value.

Sort by Key

To sort the dictionary by key, use the lambda expression kvp => kvp.Key inside the OrderBy() method:

using System.Linq;

foreach (var kvp in dictionary.OrderBy(kvp => kvp.Key))
{
    Console.WriteLine($"{kvp.Key} appeared {kvp.Value} time(s)");
}

Output (sorted by key):

apple appeared 5 time(s)
banana appeared 12 time(s)
orange appeared 15 time(s)

Sort by Value

If you prefer to sort by the dictionary values instead of keys, change the lambda to kvp => kvp.Value:

using System.Linq;

foreach (var kvp in dictionary.OrderBy(kvp => kvp.Value))
{
    Console.WriteLine($"{kvp.Key} appeared {kvp.Value} time(s)");
}

Output (sorted by value):

apple appeared 5 time(s)
banana appeared 12 time(s)
orange appeared 15 time(s)

2. Sort Dictionary in Descending Order

To sort in descending order, you can use OrderByDescending() instead of OrderBy().

Sort by Key in Descending Order

using System.Linq;

foreach (var kvp in dictionary.OrderByDescending(kvp => kvp.Key))
{
    Console.WriteLine($"{kvp.Key} appeared {kvp.Value} time(s)");
}

Output (sorted by key in descending order):

orange appeared 15 time(s)
banana appeared 12 time(s)
apple appeared 5 time(s)

Sort by Value in Descending Order

Similarly, to sort by value in descending order, use OrderByDescending() with the value lambda:

using System.Linq;

foreach (var kvp in dictionary.OrderByDescending(kvp => kvp.Value))
{
    Console.WriteLine($"{kvp.Key} appeared {kvp.Value} time(s)");
}

Output (sorted by value in descending order):

orange appeared 15 time(s)
banana appeared 12 time(s)
apple appeared 5 time(s)

3. Use a SortedDictionary

If you want the dictionary to be automatically sorted by key, you can use a SortedDictionary instead of a regular Dictionary. This collection ensures that the elements are always sorted by their keys.

Here’s an example of using a SortedDictionary:

var sortedDictionary = new SortedDictionary<string, int>()
{
    ["orange"] = 15,
    ["apple"] = 5,
    ["banana"] = 12
};

foreach (var kvp in sortedDictionary)
{
    Console.WriteLine($"{kvp.Key} appeared {kvp.Value} time(s)");
}

Output (automatically sorted by key):

apple appeared 5 time(s)
banana appeared 12 time(s)
orange appeared 15 time(s)