What is SortedDictionary in C#: Explanation and Example
SortedDictionary in C# is a collection that stores key-value pairs in sorted order by keys. It automatically keeps the keys sorted, unlike a regular dictionary which has no order. This makes it useful when you need fast lookups and ordered data.How It Works
Think of SortedDictionary like a well-organized filing cabinet where each file (key) is placed in alphabetical order. When you add a new file, it automatically finds the right spot so everything stays sorted. This means you can quickly find any file without searching through a messy pile.
Under the hood, SortedDictionary uses a balanced tree structure to keep keys sorted. This allows it to add, remove, or find items efficiently while maintaining order. Unlike a regular dictionary that stores items randomly, SortedDictionary always keeps the keys in order, which is helpful when you want to process data in a sorted way.
Example
This example shows how to create a SortedDictionary, add some items, and print them in sorted order by key.
using System; using System.Collections.Generic; class Program { static void Main() { SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>(); sortedDict.Add(3, "Apple"); sortedDict.Add(1, "Banana"); sortedDict.Add(2, "Cherry"); foreach (var item in sortedDict) { Console.WriteLine($"Key: {item.Key}, Value: {item.Value}"); } } }
When to Use
Use SortedDictionary when you need to keep data sorted by keys automatically and want fast lookups, insertions, and deletions. It is great for scenarios like:
- Maintaining a leaderboard where scores (keys) must stay sorted.
- Storing configuration settings that need to be processed in order.
- Implementing caches or indexes where order matters.
If you don't need sorted keys, a regular Dictionary might be faster. But when order is important, SortedDictionary is a simple and efficient choice.
Key Points
- Sorted by keys: Automatically keeps keys in sorted order.
- Balanced tree: Uses a tree structure for efficient operations.
- Fast lookups: Provides quick access to values by key.
- Use case: Best when order of keys matters.
- Not thread-safe: Requires external synchronization in multithreaded scenarios.