C# SortedList<TKey, TValue>
The SortedList<TKey, TValue> class is used to store the values in ascending order based on the key as an array of key/value pairs. Found in the System.Collections.Generic namespace, the C# SortedList<TKey, TValue> class contains unique keys only, thus the stored elements can be easily searched or removed using the key. The SortedList<TKey, TValue> class is similar to the SortedDictionary<TKey, TValue> class in C#.
Difference between the C# SortedList<TKey, TValue> and the C# SortedDictionary<TKey, TValue> class:
Though the use and behavior of the SortedList<TKey, TValue> class and the SortedDictionary<TKey, TValue> class are almost similar, but they yet hold some differences. The major differences between these two classes are listed below:
SortedList<TKey, TValue> class | SortedDictionary<TKey, TValue> class |
Uses less memory. | Uses more memory. |
Recommended to use for storing and retrieving the key/value pairs. | Less recommended. |
Slower insertion and removal for unsorted data. | Faster insertion and removal for unsorted data. |
Example:
using System; using System.Collections.Generic; public class Example { public static void Main(string[] args) { SortedList<string, string> countries = new SortedList<string, string>(); countries.Add("2","Mexico"); countries.Add("5","Japan"); countries.Add("1","Canada"); countries.Add("4","Nepal"); countries.Add("3","India"); foreach (KeyValuePair<string, string> i in countries) { Console.WriteLine(i.Key+" "+ i.Value); } } } |
Output:
Explanation:
In the above example, we are using the generic SortedList<TKey, TValue> class. The Add() method is used to store the elements and the for-each loop is used to iterate the elements. To get the key and value, we are using the KeyValuePair class. All the elements are stored in the SortedList<TKey, TValue> class in the ascending order based on the key, irrespective of the fact that the elements are added in ascending order or not.