Click here to Skip to main content
15,883,901 members
Articles / Programming Languages / C# 4.0
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 Jun 2010CPOL1 min read 14K   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralHi. I've also written an article on SortedSet collection. Pl... Pin
Samir NIGAM22-Jun-10 18:41
Samir NIGAM22-Jun-10 18:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.