ZetCode

C# SortedDictionary

last modified October 5, 2026

This article shows how to use SortedDictionary<TKey, TValue> in C#. It stores key-value pairs and keeps them ordered by key.

SortedDictionary<TKey, TValue> is in System.Collections.Generic. Keys are unique according to the dictionary's comparer, while values do not need to be unique. A default comparer orders keys in ascending order.

C# SortedDictionary example

Adding items in any order still produces key-sorted enumeration.

Program.cs
using System.Collections.Generic;

var scores = new SortedDictionary<string, int>();
scores.Add("Mira", 91);
scores.Add("Ada", 98);
scores.Add("Linus", 87);

foreach (var pair in scores)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}
$ dotnet run
Ada: 98
Linus: 87
Mira: 91

Adding, updating, and retrieving values

Use Add to insert a new key; it throws if that key already exists. The indexer can insert or replace a value. TryGetValue safely checks for a key and retrieves its value.

Program.cs
var inventory = new SortedDictionary<string, int>();
inventory.Add("apples", 12);
inventory["pears"] = 7;
inventory["apples"] = 15;

if (inventory.TryGetValue("apples", out int count))
{
    Console.WriteLine($"Apples: {count}");
}

Console.WriteLine($"Keys: {inventory.Count}");
$ dotnet run
Apples: 15
Keys: 2

Use ContainsKey when only checking whether a key exists. The dictionary also provides Remove and Clear for deleting entries.

Using a custom comparer

Pass an IComparer<TKey> to the constructor to change the key ordering. This example orders integer keys from largest to smallest.

Program.cs
using System.Collections.Generic;

var descending = Comparer<int>.Create((left, right) => right.CompareTo(left));
var ranks = new SortedDictionary<int, string>(descending);
ranks.Add(2, "silver");
ranks.Add(1, "gold");
ranks.Add(3, "bronze");

foreach (var pair in ranks)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}
$ dotnet run
3: bronze
2: silver
1: gold

The comparer determines both sort order and key equality. If it considers two keys equal, the dictionary treats them as the same key.

SortedDictionary or Dictionary?

Choose SortedDictionary<TKey, TValue> when ordered iteration is important or when you need to process keys in sorted order. Use Dictionary<TKey, TValue> when ordering is not needed and you want the typical faster lookup and insertion. Sorted dictionary lookups, additions, and removals take logarithmic time.

Source

SortedDictionary<TKey, TValue> Class - .NET API

This article introduced sorted key-value storage in C#.

Author

Jan Bodnar writes programming tutorials and educational content.

List all C# tutorials.