
.NET 1.1+The SortedList Collection (2)
The thirty-ninth part of the C# Fundamentals tutorial describes the use of the SortedList class. This dictionary collection provides a hybrid of the Hashtable and Array types; each entry being a key / value pair sorted according to the key's contents.
Modifying SortedList Contents
Adding an Item
All dictionary collection types that implement IDictionary include the basic Add method for adding a new item. This is supported by the SortedList class. As described above, keys must be unique and may not be null. Duplicate keys cause an ArgumentException to be thrown. If an attempt is made to add a null key, an ArgumentNullException occurs.
SortedList myList = new SortedList();
myList.Add("key1","value1");
myList.Add("key1","value2"); // Duplicate: ArgumentException
myList.Add(null,"value2"); // Null Key: ArgumentNullException
Updating Using the Key
The SortedList can be modified directly using the key as an index. If you assign a value to a key that already exists, the value of the corresponding item is updated. If the key does not exist, the key and the value are added to the SortedList as a new item.
SortedList veg = new SortedList();
veg["cabbage"] = "Red"; // New item created
veg["cabbage"] = "Savoy"; // Item updated
veg["potato"] = "King Edward";
veg["lettuce"] = "Iceberg";
veg["carrot"] = "Imperator";
Updating Using the Index Number
It is possible to access the items in a sorted list using their index numbers rather than using keys. Unlike an array, you cannot provide the index number in square brackets; this would cause conflicts between index numbers and numeric keys. To use the index number to change the value of an existing item, the SetByIndex method is called. The method has two parameters: the first is the index number of the entry to be updated, the second is the new value.
SortedList veg = new SortedList();
veg["cabbage"] = "Savoy";
veg["potato"] = "King Edward";
veg["lettuce"] = "Iceberg";
veg["carrot"] = "Imperator";
veg.SetByIndex(0, "Late Flat Dutch"); // Item updated
NB: Remember that the index number is not related to the order in which items were added to the collection. It is based upon the positions of the items after sorting. In the above example the update only works because we know that 'cabbage' is the first key when sorted alphabetically.
Removing an Item
SortedList permits items to be removed using the Remove method. This removes an item from the collection that matches a specified key. The SortedList also provides an additional method that removes an item based upon its index number. This is the RemoveAt method.
SortedList veg = new SortedList();
veg["cabbage"] = "Savoy";
veg["potato"] = "King Edward";
veg["lettuce"] = "Iceberg";
veg["carrot"] = "Imperator";
veg.RemoveAt(0); // Item removed
29 May 2007