This is the tenth part of an article on collection classes in .net with C#. This part covers the SortedList.
For the first part see http://www.audacs.co.uk/ViewPage.aspx?PageID=512
For the next part on the StringDictionary see http://www.audacs.co.uk/ViewPage.aspx?PageID=523
There are two versions of this class. The original one and the newer generic version.
These are both found at:
System.Collections.SortedList
System.Collections.Generic.SortedList
The SortedList keeps the items sorted in order of the key. It contains a collection of DictionaryEntry objects which have a key and a value;
Items in the SortedList are accessible by the key or by index as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace SortedListTest
{
class Program
{
static void Main(string[] args)
{
System.Collections.SortedList numbers = new SortedList();
numbers.Add(5, "Five");
numbers.Add(2, "Two");
numbers.Add(3, "Three");
numbers.Add(1, "One");
numbers.Add(4, "Four");
foreach (DictionaryEntry item in numbers)
{
Console.WriteLine(item.Value);
}
Console.WriteLine();
Console.Write("The item with a key of 3 is " + numbers[3]);
Console.WriteLine();
Console.Write("The second item is " + numbers.GetByIndex(1));
Console.Read();
}
}
}
The output from this program looks like this.
The generic version looks a bit different buy yields the same output:
static void Main(string[] args)
{
System.Collections.Generic.SortedList<int, string> numbers = new SortedList<int, string>();
numbers.Add(5, "Five");
numbers.Add(2, "Two");
numbers.Add(3, "Three");
numbers.Add(1, "One");
numbers.Add(4, "Four");
foreach (KeyValuePair<int, string> item in numbers)
{
Console.WriteLine(item.Value);
}
Console.WriteLine();
Console.Write("The item with a key of 3 is " + numbers[3]);
Console.WriteLine();
Console.Write("The second item is " + numbers.Values[1]);
Console.Read();
}
So you can see that there are a few differences between the generic and non generic version. The non generic version is a collection of DictionaryEntry objects but the generic version is a collection of KeyValuePair<T, T> objects.
Both allow item retrieval by key or index.
Thats really all there is to the SortedList other than a note on sorting:
The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created or according to the IComparable implementation provided by the keys themselves. In either case, a SortedList does not allow duplicate keys.
For the next part on the StringDictionary see http://www.audacs.co.uk/ViewPage.aspx?PageID=523