0
0
CsharpHow-ToBeginner · 3 min read

How to Sort Dictionary by Value in C# - Simple Guide

To sort a Dictionary<TKey, TValue> by its values in C#, use LINQ's OrderBy method on the dictionary's KeyValuePair collection. This returns an IOrderedEnumerable<KeyValuePair<TKey, TValue>> sorted by value, which you can convert back to a dictionary if needed.
📐

Syntax

Use LINQ's OrderBy method on the dictionary's entries to sort by value. Then, convert the result back to a dictionary if you want a dictionary type.

  • dictionary.OrderBy(pair => pair.Value): Sorts by the value of each key-value pair.
  • ToDictionary(pair => pair.Key, pair => pair.Value): Converts the sorted sequence back to a dictionary.
csharp
var sortedDict = dictionary.OrderBy(pair => pair.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
💻

Example

This example shows how to create a dictionary, sort it by its values in ascending order, and print the sorted key-value pairs.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var dictionary = new Dictionary<string, int>
        {
            {"apple", 5},
            {"banana", 2},
            {"cherry", 7},
            {"date", 3}
        };

        var sortedDict = dictionary.OrderBy(pair => pair.Value)
                                   .ToDictionary(pair => pair.Key, pair => pair.Value);

        foreach (var item in sortedDict)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}
Output
banana: 2 date: 3 apple: 5 cherry: 7
⚠️

Common Pitfalls

One common mistake is expecting the original dictionary to be sorted after calling OrderBy. Dictionaries do not maintain order, so you must create a new sorted collection.

Also, converting back to a dictionary loses the order because Dictionary itself is unordered. To keep order, use List<KeyValuePair<TKey, TValue>> or SortedDictionary (which sorts by key, not value).

csharp
/* Wrong: This does not sort the original dictionary */
dictionary.OrderBy(pair => pair.Value);

/* Right: Create a new sorted dictionary or list */
var sortedList = dictionary.OrderBy(pair => pair.Value).ToList();
📊

Quick Reference

OperationCode ExampleDescription
Sort by valuedictionary.OrderBy(pair => pair.Value)Sorts dictionary entries by their values ascending
Convert to dictionary.ToDictionary(pair => pair.Key, pair => pair.Value)Creates a new dictionary from sorted entries
Keep orderUse List>Preserves sorted order since Dictionary is unordered
Sort descendingdictionary.OrderByDescending(pair => pair.Value)Sorts entries by value in descending order

Key Takeaways

Use LINQ's OrderBy to sort dictionary entries by value.
Dictionaries do not maintain order; use a list to keep sorted order.
Convert sorted entries back to a dictionary if needed, but order is not guaranteed.
OrderByDescending sorts values in reverse order.
Always create a new collection when sorting dictionaries by value.