English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Object-Oriented Programming (OOP)

C# SortedList (sorted list)

SortedList<TKey, TValue> and SortedList are collection classes that can store key-value pairs sorted by key based on the associated IComparer implementation. For example, if the key is a primitive type, it is sorted in ascending order by the key.

C# Supports generic and non-generic SortedList. It is recommended to use generic SortedList<TKey, TValue> because it performs faster and is less prone to errors than non-generic SortedList.

  • SortedList Features

  • SortedList<TKey, TValue> is an array of key-value pairs sorted by key.

  • Elements are sorted immediately after they are added. Original type keys are sorted in ascending order according to IComparer<T>, and object keys are sorted.

  • It belongs to the System.Collection.Generic namespace.

  • Keys must be unique and cannot be null.

  • Values can be null or duplicate.

  • Contains elements of type KeyValuePair<TKey, TValue>

  • It uses less memory than SortedDictionary<TKey, TValue>.

  • Data retrieval is faster after sorting, while SortedDictionary<TKey, TValue> has faster speeds for inserting and deleting key-value pairs.

Create SortedList

The following example demonstrates how to create a generic SortedList<TKey, TValue> and add key-value pairs to it.

//List of integer keys, string values 
SortedList<int, string> numberNames = new SortedList<int, string>();
numberNames.Add(3, "Three");
numberNames.Add(1, "One");
numberNames.Add(2, "Two");
numberNames.Add(4, null);
numberNames.Add(10, "Ten");
numberNames.Add(5, "Five");
//The following will cause an exception
//numberNames.Add("Three", 3; //Compile-time error: Key must be of int type
//numberNames.Add(1, "One"); //Runtime exception: Key duplication
//numberNames.Add(null, "Five");//Runtime exception: The key cannot be null

In the above example, a generic SortedList<TKey, TValue> object is created by specifying the types of keys and values it needs to store. SortedList<int, string> will store int-type keys and string-type values.

The Add() method is used to add a single key-value pair to the SortedList. The key cannot be null or duplicate. If it exists, it will throw a runtime exception. The value can be duplicate, and it can be null if the type can be null.

When instantiating the SortedList instance, use collection-initializer syntax initializes with multiple key-value pairs, as shown below.

//Create a SortedList with string keys and string values 
//Using collection-initializer syntax
SortedList<string, string> cities = new SortedList<string, string>()
                                    {
                                        {"London", "UK"},
                                        {"New York", "USA"},
                                        {"Mumbai", "India"},
                                        {"Johannesburg", "South Africa"}
                                    };

After adding SortedList key-value pairs, the key-value pairs are reordered by ascending key. The following example uses a foreach loop to display all keys and values.

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {5, "Five"},
                                        {1, "One"}
                                    };
Console.WriteLine("---Initial key-value--);
foreach(KeyValuePair<int, string> kvp in numberNames)
    Console.WriteLine("key: {0}, value: {1}");1Console.WriteLine("key: {0}, value: {1}");
numberNames.Add(6, "Six");
numberNames.Add(2, "Two");
numberNames.Add(4, "Four");
Console.WriteLine("---After adding a new key-value--);
foreach (var kvp in numberNames)
    Console.WriteLine("key: {0}, value: {1}");1Console.WriteLine("key: {0}, value: {1}");
Output:
---Initial key-value--
key: 1, value: One
key: 3, value: Three
key: 5, value: Five
---After adding a new key-value--
key: 1, value: One
key: 2, value: Two
key: 3, value: Three
key: 4, value: Four
key: 5, value: Five
key: 6, value: Six

Accessing SortedList

In the indexer SortedList[key], specify a key to get or set the value in the SortedList.

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"
                                    };
1] //Output: One
2] //Output: Two
3] //Output: Three
//10] //Runtime KeyNotFoundException
numberNames[2] = "TWO"; //Update the value
numberNames[4] = "Four"; //If the key does not exist, add a new key-value

Above, numberNames[10] will throw a KeyNotFoundException because the specified key10The reason why it does not exist in sortedlist. To prevent this exception, please use ContainsKey() or TryGetValue() method as shown below.

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"
                                    };
if (numberNames.ContainsKey(4)) {
    numberNames[4] = "four";
}
int result;
if (numberNames.TryGetValue(4, out result))
    Console.WriteLine("Key: {0}, Value: ",1} 4, result);
Output:
Key:4, Value: Four

If you want to use a for loop to iterate through SortedList, please use the Keys and Values properties.

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

Delete elements from SortedList

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

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"},
                                        {5, "Five"},
                                        {4, "Four"
                                    };
    
numberNames.Remove(1;//Remove key1Yes
numberNames.Remove(10;//Remove key1Yes, there is no error if it does not exist
numberNames.RemoveAt(0);//Remove key-value pair from index 0 
//numberNames.RemoveAt(10;//Runtime exception: ArgumentOutOfRangeException
foreach (var kvp in numberNames)
	Console.WriteLine("key: {0}, value: {1}");1Console.WriteLine("key: {0}, value: {1}");
Output:
key: 3, value: Three
key: 4, value: Four
key: 5, value: Five

SortedList class hierarchy

The following figure illustrates the SortedList hierarchy.

More information about SortedList methods and properties can be found on docs.microsoft.com