Put simply, a SortedList is a Hashtable which is sorted by the keys. Like a Hashtable, it is accessible by both its keys and values. The API documentation describes a SortedList as a hybrid between a Hashtable and an Array. It behaves like a Hashtable when accessed via a key. It behaves like an Array when accessed via its GetByIndex method.
If you do not need to access elements in a SortedList via its indices, then use a Hashtable rather than a SortedList because the sorting has a performance implication, especially if you do not need that functionality.
The program below demonstrates how a SortedList can be used. The output is interspersed with the code to show the outputs of the different sections.
1: using System; 2: using System.Collections; 3: 4: public class TestClass{ 5: public static void Main(){ 6: 7: SortedList sl = new SortedList(); 8: sl.Add("A", "apple"); 9: sl.Add("E", "eggplant"); 10: sl.Add("B", "banana"); 11: sl.Add("C", "coconut"); 12: PrintCollection1(sl); 13:
Output:
Key:A Value:apple Key:B Value:banana Key:C Value:coconut Key:E Value:eggplant
Notice that, unlike a Hashtable, the elements in a SortedList are always dynamically sorted by the key every time a new element is inserted.
14: Console.WriteLine 15: ("Index of key B:" +sl.IndexOfKey("B")); 16: Console.WriteLine 17: ("Index of value apple:" +sl.IndexOfValue("apple")); 18:
Output:
Index of key B: 1 Index of value apple: 0
The IndexOfKey and IndexOfValue methods are demonstrated above.
19: sl.Add("D", "durian"); 20: PrintCollection1(sl);
Output:
Key:A Value:apple Key:B Value:banana Key:C Value:coconut Key:D Value:durian Key:E Value:eggplant
When a new key/value pair is added, the indices of all elements are updated as sorting is performed again.
21: } // end main 22: 23: // 1st way to do it 24: public static void PrintCollection1 (SortedList s){ 25: IDictionaryEnumerator enumerator = s.GetEnumerator(); 26: while (enumerator.MoveNext()) 27: Console.WriteLine("Key:" + enumerator.Key + 28: " Value:"+ enumerator.Value); 29: Console.WriteLine(); 30: } 31: 32: // 2nd way to do it 33: public static void PrintCollection2 (SortedList s){ 34: for (int i=0; i<s.Count; i++) 35: Console.WriteLine("Key:" + s.GetKey(i) + 36: " Value:"+ s.GetByIndex(i)); 37: Console.WriteLine(); 38: } 39: }
Both PrintCollection1 and PrintCollection2 are functionally identical. Since the elements in a SortedList are indexed, you can use the GetByIndex and GetKey methods to retrieve a value or key by its index respectively (lines 35 – 36).
A SortedList has the following public properties – Count, Keys, Values; and the following methods – ContainsKey, ContainsValue, Remove. These properties and methods are used in exactly the same way as in a Hashtable class and are therefore not included in this example again.
18.216.250.53