C# Generic SortedDictionary

A generic sorted dictionary in C# is very similar to a generic dictionary, as it stores data in key and value pairs. The key difference however, is the order of the key and value pairs. Whilst a generic dictionary stores its contents in the order that it was added, a generic sorted dictionary stores its key and value pairs in ascending order of the key.

Below is an example of a sorted dictionary, called ‘people’, where the key is a string, that holds a person’s name and the value is an integer for their age.

SortedDictionary<string, int> people = new SortedDictionary<string, int>();
people.Add("Bob Smith", 30);
people.Add("George Jones", 21);
people.Add("Fred Bloggs", 43);
people.Add("Alan White", 29);

The first line declares the sorted dictionary, with a string for the key and an integer for the value. Four key and value pairs are then added to the sorted dictionary using its ‘Add’ method, with a person’s name as the key and their age as the value.

The declaration and initialisation can be combined into one statement, so the above could be re-written as follows.

SortedDictionary<string, int> people = new SortedDictionary<string, int>()
{
    {"Bob Smith", 30},
    {"George Jones", 21},
    {"Fred Bloggs", 43},
    {"Alan White", 29}
};

It is possible to see how many key and value pairs there are in the sorted dictionary using the ‘Count’ property of the sorted dictionary itself.

Console.WriteLine(people.Count);

As with other collections, it is possible to loop through a sorted dictionary using a ‘foreach’ loop. Here, the key and value for each person are incorporated in to a sentence stating a person’s age. The curly braces that contain a number are placeholders for the key and value of the dictionary.

foreach (KeyValuePair<string, int> person in people)
{
    Console.WriteLine("{0} is {1} years old.", person.Key, person.Value);
}

The output in the console from the above example is as follows.

Bob Smith is 30 years old.
George Jones is 21 years old.
Fred Bloggs is 43 years old.
Alan White is 21 years old.

It is also possible to access a single value if the key is known.

Console.WriteLine(people["Bob Smith"]);

Sorted dictionaries share the flexibility of generic lists with the ease of adding, updating and removing key and value pairs. Here a key of ‘John Smith’, with a value of ‘52’ is added to the ‘people’ sorted dictionary.

people.Add("John Smith", 52);

Note that if the key ‘John Smith’ already exists, then an error will be produced. To stop this from happening the ‘ContainsKey’ sorted dictionary method could be used to check to see if the key already exists before adding it.

if (!people.ContainsKey("John Smith"))
{
    people.Add("John Smith", 52);
}

To update a value in a sorted dictionary, the sorted dictionary name and key need to be specified.

people["Bob Smith"] = 100;

Note that if the key specified doesn’t already exist, then this has the same effect as using the sorted dictionary ‘Add’ method, where a new key and value pair are added to the sorted dictionary.

Removing a key and value pair from a sorted dictionary is simply a matter of using the ‘Remove’ method and specifying the key.

people.Remove("George Jones");

Finally, if it is necessary to remove all items in a sorted dictionary in one go, instead of individually with the ‘Remove’ method, there is a ‘Clear’ method to accomplish this.

people.Clear();

On the face of it both a generic sorted dictionary and a generic sortedlist look identical, however, there are some differences which should be considered when choosing between the two. Firstly a sortedlist uses less memory than a sorted dictionary. Secondly, a sorted dictionary provides faster insertion and removal operations for unsorted data, however, if a sortedlist is populated all at once from sorted data then it is faster than a sorted dictionary.

Further Reading