Working with SortedSet in .NET 4.0

By | June 26, 2011

SortedSet is one class that is been added to the .Net class library 4.0 which actually merges the behaviour of HashSet and SortedList together. It maintains the sorted ordering of the list without affecting performance.

Lets see how it works :

SortedSet<int> sorted = new SortedSet<int> { 1, 43, 65, 23, 44, 56, 43, 1, 56, 66, 24 };
 foreach(int number in sorted)
   {
      Console.WriteLine(number);
 }
Console.Read();

Here is the out put for the above code block

Now if you see the output closely, you will notice that the output actually removes the duplicate entries and also sorts each of them. The HashSet actually maintains the sorting even if you remove an element or add an element from the list.

Hence, sorted.Add(60); will add a new element between 56 and 65 .
The Add method returns true if the element gets inserted, or otherwise returns false if the list already contains the element.
SortedSet also allows you to project a view between two ranges. Lets see how you can achieve this :

SortedSet<int> view = sorted.GetViewBetween(30, 50);

Here the view actually contains the elements between numbers 30 and 50.

You are also allowed to pass your own custom Comparer when you want to do this for your own type.

SortedSet<MyType> animal = new SortedSet<MyType>(new MyTypeComparer());

This will ensure that the comparison between two object will be done using MyTypeComparer rather than using Hash value.

Now how does it do all sorting without affecting performance. Well, if you dig deep into the structure of SortedSet, it actually maintains a AVL tree inside. So when you add an element it actually checks all the nodes before putting it as leaf.

I hope this helps you.
Happy Coding.