Working with SortedSet in .NET 4.0

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)

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434