.NET 4 Baby Steps: Part VI - SortedSet

Submitted by Robert MacLean on Mon, 05/10/2010 - 10:42

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

SortedSet<T> provides a way to have a sorted list of items, which is sorted internally in a binary tree. This is different to the index  based sorting on SortedList<T, K> or SortedDictionary<T, K>. This means that inserts and edits to the tree are done with almost no perf impact and it also means we do not need to figure out the key manually. Without an index, you may ask how does it know the sort order? The answer is that the class it is using 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<T>

Under the surface SortedSet<T> implements the new ISet<T> interface, which is especially designed for collections with unique items. HashedSet<T>, which was introduced in 3.5, has also been updated to implement ISet<T>.