Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

SortedSet(T), just another collection in .NET 4.0?

0.00/5 (No votes)
21 Jun 2010 1  
With SortedSet<T> we have another specialized built in collection in the base class library. For all who now thinks, i don't need another specialized collection, there are enough, I only need the List and Dictionary, it is really useful and you will be happy if you know that there a collection like this which is built in.
It's in the namespace System.Collections.Generic. It is similar to HashSet<T>, a collection of unique elements, but the elements will stay sorted. Duplicate items can be added with no error, but they will be ignored. So if two identical values are added you will only have one item in your collection. Also the add method returns true or false if the value is already added or not. Pay attention, the SortedSet<T> has lesser performance than the HashSet<T>, so it only should be used if you really need a collection which is sorted.
C#
SortedSet<int> set = new SortedSet<int> {10, 12, 1, 5, 1};
foreach (int item in set)
{
    Console.WriteLine(item);
}

In the example a SortedSet of int is initialized. Integers are added in no particular order, also duplicated values (1). On the console there are only show 4 values, 1 only appears one time. The integers will appear on the console in a sorted order. So SortedSet<T> is the solution if you need a list of unique items which should stay sorted.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here