.NET 4 Baby Steps: Part VI - SortedSet

Note: This post is part of a series and you can find the rest of the parts in the series index.

SortedSet provides a way to have a sorted list of items, which is sorted internally in a binary tree. This is different from the index-based sorting in SortedList<T, K> or SortedDictionary<T, K>. This means that inserts and edits to the tree have almost no performance impact, and it also means we do not need to figure out the key manually. Without an index, you may ask how it knows the sort order? The answer is that the class it uses must implement IComparable, so it can sort correctly:

Usage is very simple:

public static void Main()
{
    Random random = new Random();
    SortedSet<GPSPosition> gpsPositions = new SortedSet<GPSPosition>();
    for (int counter = 0; counter < 100000; counter++)
    {
        gpsPositions.Add(new GPSPosition(random.Next(-180, 181), random.Next(-180, 181)));
    }

    foreach (GPSPosition position in gpsPositions)
    {
        Console.WriteLine(position);
    }
}

Note: I am using the same GPSPosition class from part IV. This gives the following output:

image

ISet

Under the surface, SortedSet implements the ISet interface, which is designed especially for collections with unique items. HashSet (not HashedSet), which was introduced in .NET 3.5, has also been updated to implement ISet.