0
0
CsharpHow-ToBeginner · 3 min read

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

To sort a dictionary by key in C#, use OrderBy from LINQ to create a sorted sequence or use SortedDictionary<TKey, TValue> which keeps keys sorted automatically. Both methods let you access dictionary entries in key order.
📐

Syntax

Here are two common ways to sort a dictionary by key in C#:

  • Using LINQ: var sorted = dictionary.OrderBy(pair => pair.Key);
  • Using SortedDictionary: var sortedDict = new SortedDictionary<TKey, TValue>(dictionary);

OrderBy returns an IOrderedEnumerable sorted by keys. SortedDictionary stores items sorted by keys automatically.

csharp
var sorted = dictionary.OrderBy(pair => pair.Key);

var sortedDict = new SortedDictionary<TKey, TValue>(dictionary);
💻

Example

This example shows how to sort a dictionary by key using both LINQ and SortedDictionary, then prints the sorted keys and values.

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

class Program
{
    static void Main()
    {
        var dictionary = new Dictionary<int, string>
        {
            {3, "Three"},
            {1, "One"},
            {4, "Four"},
            {2, "Two"}
        };

        // Sort using LINQ OrderBy
        var sortedByLinq = dictionary.OrderBy(pair => pair.Key);
        Console.WriteLine("Sorted by LINQ OrderBy:");
        foreach (var pair in sortedByLinq)
        {
            Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
        }

        // Sort using SortedDictionary
        var sortedDict = new SortedDictionary<int, string>(dictionary);
        Console.WriteLine("\nSorted using SortedDictionary:");
        foreach (var pair in sortedDict)
        {
            Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
        }
    }
}
Output
Sorted by LINQ OrderBy: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three Key: 4, Value: Four Sorted using SortedDictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three Key: 4, Value: Four
⚠️

Common Pitfalls

Common mistakes when sorting dictionaries by key include:

  • Expecting Dictionary<TKey, TValue> itself to be sorted. It is not ordered.
  • Using OrderBy but forgetting to enumerate or convert the result, so no sorting happens.
  • Modifying the original dictionary while enumerating the sorted sequence, causing errors.

Always use the sorted result separately or use SortedDictionary if you want automatic sorting.

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

/* Right: Use the sorted sequence or create a new sorted dictionary */
var sorted = dictionary.OrderBy(pair => pair.Key);

var sortedDict = new SortedDictionary<int, string>(dictionary);
📊

Quick Reference

MethodDescriptionUsage
LINQ OrderByReturns sorted sequence by keyvar sorted = dictionary.OrderBy(pair => pair.Key);
SortedDictionaryStores keys sorted automaticallyvar sortedDict = new SortedDictionary(dictionary);

Key Takeaways

Use LINQ OrderBy to get a sorted sequence of dictionary entries by key.
SortedDictionary keeps keys sorted automatically and can be used instead of Dictionary.
Dictionary itself does not maintain order; sorting requires extra steps.
Always enumerate or convert the sorted result to see sorted output.
Avoid modifying the dictionary while iterating over a sorted sequence.