C# Generic SortedList

A generic sortedlist in C# is much like its non-generic counterpart, they store data in key and value pairs, however, as with other generic collections, the data type is required to be specified, for both the key and the value. The key and value pairs are stored in ascending order of the key. The keys must be unique and cannot be null, unlike the values, where both nulls and duplicates are allowed.

The example below shows the declaration of a generic sortedlist, with four items added to it using the 'Add' method. All of the keys are strings, containing a person's name, whilst all the values are numeric, comprising of an age, corresponding to the name in the key.

SortedList<string, int> people = new SortedList<string, int>();

people.Add("Bob Smith", 30);
people.Add("George Jones", 21);
people.Add("Fred Bloggs", 43);
people.Add("Alan White", 29);

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

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

Regardless of the method used to declare and initialise the generic sortedlist, a 'foreach' loop can be used to process its contents. 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 generic sortedlist.

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. Notice that the order of the items differs from how they were added to the generic sortedlist, as they now appear in ascending order of the key.

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

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

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

If it is necessary to find out how many key and value pairs exist in a generic sortedlist, then the 'Count' property can be used to achieve this.


This could be utilised, for example, if an ordinary 'for' loop were to be used, instead of a 'foreach' loop.

In order to check whether a specific key or value exists in a generic sortedlist, the 'ContainsKey' and 'ContainsValue' methods can be used, both of which return a Boolean 'True' or 'False' value.

Console.WriteLine(people.ContainsKey("Fred Bloggs"));

As well as adding new items using the 'Add' method, there is also a 'Remove' method, to remove a specific key and value pair, if the key is known.

people.Remove("Fred Bloggs");

To remove all values in a generic sortedlist, instead of removing each key and value pair, one at a time, using the 'Remove' method, there is a 'Clear' method that will achieve this in one statement.


Further Reading