Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

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

, 21 Jun 2010
Rate this:
Please Sign up or sign in to vote.
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.
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)

Share

About the Author

Mattia Baldinger
Software Developer
Switzerland Switzerland
No Biography provided
Follow on   Twitter

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 22 Jun 2010
Article Copyright 2010 by Mattia Baldinger
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid