C# SortedDictionary
A SortedDictionary is a dictionary that keeps its pairs ordered by key. Reading the pairs back gives them in key order with no extra sorting code.
Pairs Print in Key Order
The pairs go in out of order. The loop prints them sorted by key with no sorting code.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
SortedDictionary<string, int> stock = new SortedDictionary<string, int>();
stock["pear"] = 4;
stock["apple"] = 9;
stock["plum"] = 2;
foreach (KeyValuePair<string, int> pair in stock)
{
Console.WriteLine(pair.Key + ": " + pair.Value);
}
}
}Number Keys Sort as Numbers
The keys here are room numbers. They print in rising number order.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
SortedDictionary<int, string> rooms = new SortedDictionary<int, string>();
rooms[305] = "Lab";
rooms[101] = "Office";
rooms[210] = "Studio";
foreach (KeyValuePair<int, string> pair in rooms)
{
Console.WriteLine(pair.Key + ": " + pair.Value);
}
}
}Read and Update by Key
Assigning to the key apple replaces its count. ContainsKey and Count then report on the dictionary.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
SortedDictionary<string, int> stock = new SortedDictionary<string, int>();
stock["pear"] = 4;
stock["apple"] = 9;
stock["apple"] = 10;
Console.WriteLine(stock["apple"]);
Console.WriteLine(stock.ContainsKey("pear"));
Console.WriteLine(stock.Count);
}
}Example
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
SortedDictionary<string, int> prices = new SortedDictionary<string, int>();
prices["Tea"] = 3;
prices["Coffee"] = 5;
prices["Juice"] = 4;
prices.Remove("Tea");
foreach (KeyValuePair<string, int> pair in prices)
{
Console.WriteLine(pair.Key + ": " + pair.Value);
}
Console.WriteLine("Items: " + prices.Count);
}
}Key points
- SortedDictionary<K, V> pairs each key with one value, like a plain Dictionary.
- Pairs are stored in key order at all times.
- Adding pairs in any order still reads them back sorted by key.
- A foreach loop over a SortedDictionary visits the pairs in key order.
- The indexer reads and updates a value by key, as in a plain Dictionary.
- A plain Dictionary needs its keys copied and sorted for an ordered listing.
In this example, the SortedDictionary holds a price for each drink. Remove deletes the pair for Tea. The loop prints the two pairs left in key order, Coffee and then Juice. The last line prints the Count, which is 2.
Note
The order comes from the keys alone. The values play no part in the ordering.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In what order does a SortedDictionary store its pairs?