Click here to Skip to main content
Click here to Skip to main content
Go to top

An Introduction to SortedSet Collection of .NET 4.0

, 25 Oct 2010
Rate this:
Please Sign up or sign in to vote.
This article will introduce some of the benefits of using SortedSet.

Introduction

.NET 4.0 includes a new collection of objects that maintains the element list in sorted order.

1.jpg

It is in the System Assembly and comes in the System.Collections.Generic namespace.

An Inside Look

The SortedSet implements a variety of interfaces:

2.jpg

A brief of some of the interfaces is as under:

ISet<T >

Provides the base interface for the abstraction of sets.

IDeserializationCallback

Indicates that a class is to be notified when deserialization of the entire object graph has been completed.

Using the Code

Let us see some examples as what we can do with this new friend.

Example 1: Display Elements

3.jpg

Consider this simple program.

We have created a new SortedSet whose type is integer and assign some random values to it. Out of which the number 100 has appeared twice.

Running the program yields:

4.jpg

As can be inferred that, the duplicate element has been removed and sorting happens.

Next consider this:

5.jpg

The name Niladri has appeared thrice with one being in complete upper case.

Upon running, we get:

6.jpg

As can be inferred that, it removes Niladri which are of the same case but not the UpperCase one.

Example 2: GetViewBetween

This method yields a subset view that contains only the values in the specified range.

Suppose we want to view the elements between A to C.

stringElementSet.GetViewBetween("A","C").ToList().ForEach(i => Console.WriteLine(i));

The output is as expected:

Arina
Biswas

Example 3: Adding a new element

We can use the Add method for adding the element in the sorted list. It returns true or false depending on whether the element has been added successfully or not.

E.g.

7.jpg

We already have an element by the name Arina in our list and henceforth the Add method returns false because we have already seen in the first example that the sorted set removes the duplicate element and then sorts. Henceforth, the result False is in perfect accordance.

But if we add something as Arina Biswas, that will get added perfectly.

Example 4: Removing an element /Elements

Sorted list provides two methods for removing elements:

a) public bool Remove(T item);

Removes a specified item from the System.Collections.Generic.SortedSet<t>. e.g.

stringElementSet.Remove("Niladri");

b) public int RemoveWhere(Predicate<T> match);

Removes all elements that match the conditions defined by the specified predicate from a System.Collections.Generic.SortedSet<T>. e.g.

stringElementSet.RemoveWhere(i => i.StartsWith("N"));

As can be figured out, we are removing those names from the collection whose names starts with N.

Example 5: Overlaps

It is a very handy method which tells whether the current System.Collections.Generic.SortedSet object and a specified collection share common elements. e.g.:

var stringDifferentElementSet = new SortedSet<string /> { "SomeotherElements" };
bool res = stringElementSet.Overlaps(stringDifferentElementSet);

will yield false because there are no common elements.

But if we change the set to:

var stringDifferentElementSet = new SortedSet<string /> { "SomeotherElements","NILADRI" };

the output will be true as NILADRI is a common element between two sets.

Example 6: CopyTo method

The CopyTo method of SortedSet copies the elements to a compatible one dimension array.

It has three overloaded methods.

1) First Overloaded Method
public void CopyTo(T[] array);

Purpose: Copies the complete System.Collections.Generic.SortedSet to a compatible one-dimensional array, starting at the beginning of the target array. E.g.

string[] arr = new string[stringElementSet.Count];
stringElementSet.CopyTo(arr);

Output:

8.jpg
2) Second Overloaded Method
public void CopyTo(T[] array, int index);

Purpose: Copies the complete System.Collections.Generic.SortedSet to a compatible one-dimensional array, starting at the specified array index. E.g.

string[] arr = new string[stringElementSet.Count + 1];
stringElementSet.CopyTo(arr,1);
9.jpg

Since the copy operation started from the 1st element, hence the zeroth index is zero.

3) Third Overloaded Method
public void CopyTo(T[] array, int index, int count);

Purpose: Copies a specified number of elements from System.Collections.Generic.SortedSet to a compatible one-dimensional array, starting at the specified array index. E.g.

string[] arr = new string[stringElementSet.Count];
stringElementSet.CopyTo(arr, 1,2);

Here, the copy operation started from the 1st array index and we will pick up the first two elements from the SortedList.

The output is as expected:

10.jpg

Example 7: Merge/Combine two Sorted Sets

A) Union

Produces the set union of two sequences by using the default equality comparer.

Consider the below two sets:

var stringElementSet = new SortedSet<string> 
	{ "Niladri", "NILADRI", "Arina", "Biswas", "Niladri" };
var stringSecondElementSet = new SortedSet<string> { "0", "1","2","3","4" };

Running the following...

stringElementSet.Union(stringSecondElementSet).ToList()
.ForEach(i => Console.WriteLine(i));

...yields the below output:

11.jpg
B) UnionWith

Modifies the current SortedSet object so that it contains all elements that are present in both the current object and in the specified collection.

stringElementSet
.UnionWith(stringSecondElementSet);

stringElementSet
.ToList()
.ForEach(i => Console.WriteLine(i));

Output:

12.jpg2

Example 8: Intersect - Find the common elements

Consider...

var stringElementSet = new SortedSet<string> { "Niladri", ""Arina", "Biswas};
var stringSecondElementSet = new SortedSet<string> {"Hello", "Niladri" };

...performing a...

stringElementSet
	.Intersect(stringSecondElementSet)
	.ToList()
	.ForEach(i => Console.WriteLine(i));

...will result into Niladri since it is common element.

Example 9: Except – Difference of two sets

E.g.

stringElementSet
.Except(stringSecondElementSet)
.ToList()
.ForEach(i => Console.WriteLine(i)); 

will give:

Arina and Biswas

But...

stringSecondElementSet
.Except(stringElementSet)
.ToList()
.ForEach(i => Console.WriteLine(i));

...will give the output as Hello.

Example 10: IntersectWith- Remove all elements that are not in both the sets

E.g.

stringElementSet.IntersectWith(stringSecondElementSet);

will give the output as Niladri.

Example 11: SymmetricExceptWith – Keeps the unique elements from both the sets and remove the common ones

E.g.

stringElementSet.SymmetricExceptWith(stringSecondElementSet);

will remove Niladri and give the output as:

Arina
Biswas
Hello

Example 12: Max and Min Property

Gets the Max element and Min element in the list respectively. E.g.

Console.WriteLine("Min element is {0} and Max is {1} "
						,stringElementSet.Min
						,stringElementSet.Max);

Will give the output as "Min element is Arina and Max is NILADRI".

Conclusion

This tutorial describes some of the methods of the SortedSet. Hope this helps.

Comments on the topic are highly appreciated for the improvement of the topic.

Thanks for reading the article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Niladri_Biswas
Software Developer (Senior)
India India
Working as a s/w engineer in HCL

Comments and Discussions

 
Generalnice PinmemberPranay Rana17-Jan-11 1:23 
GeneralMy vote of 5 PinmemberEshwer27-Oct-10 7:46 
GeneralMy vote of 1 PinmemberM8ix26-Oct-10 18:34 
GeneralMy vote of 5 Pinmemberdepakb26-Oct-10 17:54 
GeneralMy vote of 1 PinmemberJRiggs26-Oct-10 8:54 
GeneralAlready Been Done - By Me PinmemberKevin Marois26-Oct-10 5:49 
GeneralMy vote of 1 PinmemberHimanshuJoshi26-Oct-10 5:11 
GeneralMy vote of 1 PinmemberDeyan Georgiev26-Oct-10 3:44 
GeneralMy vote of 1 PinmemberJF201526-Oct-10 2:36 
GeneralMy vote of 1 PinmemberSlacker00726-Oct-10 2:36 
GeneralMy vote of 1 PinmemberTheyCallMeMrJames26-Oct-10 2:25 
GeneralMy vote of 1 PinmemberOriginalGriff26-Oct-10 2:20 
GeneralMy vote of 1 PinmvpHenry Minute26-Oct-10 2:17 
GeneralMy vote of 1 Pinmemberleppie26-Oct-10 2:11 
GeneralMy vote of 1 PinmemberSeishin#26-Oct-10 2:10 
GeneralI can read MSDN on my own, you know.. PinmemberSeishin#26-Oct-10 2:10 
GeneralRe: I can read MSDN on my own, you know.. PinmemberKhaniya26-Oct-10 3:45 
GeneralRe: I can read MSDN on my own, you know.. PinmemberSeishin#26-Oct-10 3:48 
GeneralMy vote of 3 Pinmembertaras_b26-Oct-10 0:32 
GeneralRe: My vote of 3 PinmemberToli Cuturicu26-Oct-10 2:01 
GeneralRe: My vote of 3 [modified] Pinmembertaras_b26-Oct-10 2:39 
GeneralGood article Pinmemberclew_bel25-Oct-10 21:36 

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 26 Oct 2010
Article Copyright 2010 by Niladri_Biswas
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid