Read the syntax
Maintain key-based sorted traversal with a comparer that also determines key equivalence.
SortedDictionary enumerates the integer keys in ascending comparer order.
What it is and why to use it
A normal dictionary is designed for key lookup, not a sorted presentation contract. SortedDictionary maintains keys in comparer order as entries are added and removed. Use it when a changing map needs sorted traversal repeatedly; sorting once at display time may be simpler for mostly static data.
How it works
The comparer orders keys and determines whether two keys are equivalent: a comparison result of zero denotes the same key. Add rejects an existing equivalent key, while the indexer updates its value. Traversal follows key order rather than value order. Choose a comparer suitable for identifiers or linguistic presentation, depending on the domain.
Common mistakes and limitations
Do not mutate comparison-defining key state after insertion. Do not assume equal values imply equal keys or that sorting is free. A case-insensitive comparer can make differently cased strings address the same entry, which should be an intentional policy.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
var map = new SortedDictionary<int, string>();Examples
Traverse keys in sorted order
Insert entries out of order and inspect the traversal.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var lessons = new SortedDictionary<int, string> {
[20] = "Functions", [10] = "Arrays", [30] = "Classes"
};
foreach (var pair in lessons) Console.WriteLine($"{pair.Key}: {pair.Value}");
- Insertion order differs from key order.
- SortedDictionary enumerates the integer keys in ascending comparer order.
- Values are printed beside their keys; they are not themselves alphabetically sorted.
- Expected output: 10: Arrays 20: Functions 30: Classes
- Choose a key comparer deliberately.
Let the comparer define equivalent keys
Update one logical identifier using a different letter case.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var counts = new SortedDictionary<string, int>(StringComparer.OrdinalIgnoreCase);
counts["PHP"] = 1;
counts["php"] = 2;
Console.WriteLine(counts.Count);
Console.WriteLine(counts["PHP"]);
- The comparer treats the two key spellings as equivalent.
- The second indexer assignment updates that entry rather than adding another key.
- The result is one entry with value two. A case-sensitive domain should choose a different comparer.
- Expected output: 1 2
- Choose a key comparer deliberately.
Best practices
- Choose a key comparer deliberately.
- Use sorting at display time when maintaining order continuously is unnecessary.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference