SortedDictionary
Learn ordered key collections with SortedDictionary<K,V>.
SortedDictionary<K,V>
A SortedDictionary<K,V> keeps keys ordered at all times. It uses a red-black tree internally; each insert and delete rebalances the tree.
Ordering follows the key's CompareTo method. A foreach loop yields keys in ascending order. Lookup is slower than Dictionary<K,V> but ordered iteration is guaranteed.
Dictionary vs SortedDictionary
Dictionary<K,V> is hash-based; lookup is roughly O(1) but keys iterate unordered. SortedDictionary<K,V> is tree-based; lookup is O(log n) but ordered iteration is guaranteed.
Choose SortedDictionary for a report or menu needing ordered output. If fast lookup matters most and order is irrelevant, Dictionary is the better fit.
Exercise Print keys in order
Three fruits were added to the prices sorted dictionary below. Use foreach to print each key in sorted order with Console.WriteLine.
Show example solution
Iterate with foreach over a kvp variable, print kvp.Key each step.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var prices = new SortedDictionary<string, int>();
prices.Add("cherry", 2);
prices.Add("apple", 5);
prices.Add("pear", 3);
foreach (var kvp in prices)
{
Console.WriteLine(kvp.Key);
}
}
}
Test yourself
-
Match the collection to its ordering
- Dictionary<K,V>
- Unordered
- SortedDictionary<K,V>
- Tree-based sorted
- SortedList<K,V>
- Array-based sorted
-
SortedDictionary declaration
var prices = new SortedDictionary<____>();Show answer
var prices = new SortedDictionary<string, int>(); -
When is SortedDictionary preferred?
- When fastest lookup is needed
- When memory saving is needed
- When keys must be iterated in order
- When there are few items
Show answer
When keys must be iterated in order — Correct. SortedDictionary is used when ordered iteration is needed.