C# - SortedList

The SortedList is a collection type that stores key-value pairs in the ascending order of key.

C# supports generic and non-generic SortedList. You must specify the type of keys and values in the generic SortedList<TKey, TValue>, whereas in the non-generic SortedList, they can be of any data type.

Note:
It is recommended to use generic SortedList<TKey, TValue> because it performs faster than non-generic SortedList and compile-time type checking removes the possibility of errors at run-time.

Creating a SortedList

The generic SortedList denotes with angel bracket SortedList<TKey, TValue> where TKey is the type of keys, and TValue is the type of values.

The following example demonstrates creating a generic SortedList.

Example: Instantiate SortedList
//int keys, string values
SortedList<int, string> mySortedList1 = new SortedList<int,string>(); 

//string keys, int values
SortedList<string, int> mySortedList2 = new SortedList<string,int>(); 

Adding Elements in SortedList

Use the Add() method to add key-value pairs into a SortedList. Keys cannot be null or duplicate. If found, it will throw a run-time exception. Values can be duplicate and null if the type is nullable.

Signature: void Add(TKey key, TValue value)

Example:Add Elements in Generic SortedList
SortedList<int,string> sl1 = new SortedList<int,string>();
sl1.Add(3, "Three");
sl1.Add(1, "One");
sl1.Add(2, "Two");
sl1.Add(4, null);
//sl1.Add("Three", 3); //Error: cannot convert string to int key

// the following will throw run-time exceptions
//sl1.Add(1, null); // duplicate key
//sl1.Add(null, "Five");// key cannot be null

SortedList<string, int> sl2 = new SortedList<string,int>();
sl2.Add("I", 1);
sl2.Add("II", 2);
sl2.Add("III", 3);
//sl2.Add(null, 4); // run-time exception: key cannot be null 

The key-value pairs can also be added using object-initializer syntax, as shown below.

Example: Add Elements in SortedList
SortedList<int,string> mySL = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two")}
                                    };
Note:
The SortedList rearranges key-value pairs in the ascending order of keys as soon as a key-value pair added.

Accessing SortedList

Specify a key in the indexer sortedList[key], to get or set a value in the SortedList.

Example: Access SortedList Values
SortedList<int,string> numToName = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"}
                                    };

var value = numToName[1];
//var value2 = numToName[10]; //run-time KeyNotFoundException

numToName[2] = "Two-2"; //updates value
numToName[4] = "Four"; //adds a new key-value if a key does not exists

Above, var value = numToName["ten"]) will throw a KeyNotFoundException because specified key "ten" does not exits. To prevent this exception, use ContainsKey() or TryGetValue() methods, as shown below.

Example: Access SortedList Values
SortedList<int,string> numToName = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"}
                                    };
if(numToName.ContainsKey(4))
    numToName[4] = "four";

int value;
if(!numToName.TryGetValue(5, out value))
    numToName[5] = "five"; 

Iterate SortedList using foreach loop

The foreach loop can be used to iterate a SortedList collection. The SortedList includes key-value pairs. So, the type of element would be KeyValuePair structure.

foreach statement to access generic SortedList:
SortedList<int,string> numToName = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"}
                                    };

foreach(KeyValuePair<int, string> kvp in numToName)
    Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );

foreach(var kvp in numToName)
    Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );
Output:
key: 1, value: One
key: 2, value: Two
key: 3, value: Three

Notice that the SortedList sorts key-value pairs by ascending order of its keys.

Use Keys and Values properties if you want to iterate a SortedList using a for loop.

Example: Iterate using For Loop
SortedList<int,string> numToName = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"}
                                    };
for (int i = 0; i < numToName.Count; i++)
{
    Console.WriteLine("key: {0}, value: {1}", numToName.Keys[i], numToName.Values[i]);
}
Output:
key: 1, value: One
key: 2, value: Two
key: 3, value: Three

Remove Elements from SortedList

Use the Remove(key) and RemoveAt(index) methods to remove key-value pairs from a SortedList.

Example: Remove Elements
SortedList<int,string> numToName = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"}
                                    };
    
numToName.Remove(1);//removes key 1 pair
numToName.RemoveAt(0);//removes key-value pair from index 0 

SortedList Properties

Property Description
Count Gets the number of key-value pairs contained in the SortedList.
Item[TKey] Gets or sets the value associated with the specified key.
Keys Get a collection of keys in the SortedList.
Values Get a collection of values in the SortedList.

SortedList Methods

Method Description
Add(TKey key, TValue value) Add key-value pairs into the SortedList.
Remove(TKey key) Removes a key-value pair with the specified key.
RemoveAt(int index) Removes a key-value pair from the specified index.
Contains(TKey key) Checks whether specified key exists in SortedList.
Clear() Removes all the elements from SortedList.

Learn more about the SortedList here.