Click here to Skip to main content
15,885,032 members
Articles / Programming Languages / C# 4.0

An Introduction to SortedSet Collection of .NET 4.0

Rate me:
Please Sign up or sign in to vote.
3.15/5 (29 votes)
25 Oct 2010CPOL4 min read 46.8K   110   10   22
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.

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.

C#
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.

C#
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<t /> object and a specified collection share common elements. e.g.:

C#
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:

C#
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
C#
public void CopyTo(T[] array);

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

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

Output:

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

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

C#
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
C#
public void CopyTo(T[] array, int index, int count);

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

C#
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:

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

Running the following...

C#
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.

C#
stringElementSet
.UnionWith(stringSecondElementSet);

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

Output:

12.jpg2

Example 8: Intersect - Find the common elements

Consider...

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

...performing a...

C#
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.

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

will give:

C++
Arina and Biswas

But...

C#
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.

C#
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.

C#
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.

C#
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)



Comments and Discussions

 
Generalnice Pin
Pranay Rana17-Jan-11 1:23
professionalPranay Rana17-Jan-11 1:23 
GeneralMy vote of 5 Pin
Eshwer27-Oct-10 7:46
Eshwer27-Oct-10 7:46 
GeneralMy vote of 1 Pin
M8ix26-Oct-10 18:34
M8ix26-Oct-10 18:34 
GeneralMy vote of 5 Pin
depakb26-Oct-10 17:54
depakb26-Oct-10 17:54 
GeneralMy vote of 1 Pin
Jay Riggs26-Oct-10 8:54
Jay Riggs26-Oct-10 8:54 
GeneralAlready Been Done - By Me Pin
Kevin Marois26-Oct-10 5:49
professionalKevin Marois26-Oct-10 5:49 
GeneralMy vote of 1 Pin
HimanshuJoshi26-Oct-10 5:11
HimanshuJoshi26-Oct-10 5:11 
GeneralMy vote of 1 Pin
Single Step Debugger26-Oct-10 3:44
Single Step Debugger26-Oct-10 3:44 
GeneralMy vote of 1 Pin
JF201526-Oct-10 2:36
JF201526-Oct-10 2:36 
GeneralMy vote of 1 Pin
Slacker00726-Oct-10 2:36
professionalSlacker00726-Oct-10 2:36 
GeneralMy vote of 1 Pin
TheyCallMeMrJames26-Oct-10 2:25
TheyCallMeMrJames26-Oct-10 2:25 
GeneralMy vote of 1 Pin
OriginalGriff26-Oct-10 2:20
mveOriginalGriff26-Oct-10 2:20 
GeneralMy vote of 1 Pin
Henry Minute26-Oct-10 2:17
Henry Minute26-Oct-10 2:17 
GeneralMy vote of 1 Pin
leppie26-Oct-10 2:11
leppie26-Oct-10 2:11 
GeneralMy vote of 1 Pin
Seishin#26-Oct-10 2:10
Seishin#26-Oct-10 2:10 
GeneralI can read MSDN on my own, you know.. Pin
Seishin#26-Oct-10 2:10
Seishin#26-Oct-10 2:10 
GeneralRe: I can read MSDN on my own, you know.. Pin
Khaniya26-Oct-10 3:45
professionalKhaniya26-Oct-10 3:45 
GeneralRe: I can read MSDN on my own, you know.. Pin
Seishin#26-Oct-10 3:48
Seishin#26-Oct-10 3:48 
GeneralMy vote of 3 Pin
taras_b26-Oct-10 0:32
taras_b26-Oct-10 0:32 
GeneralRe: My vote of 3 Pin
Toli Cuturicu26-Oct-10 2:01
Toli Cuturicu26-Oct-10 2:01 
No explanation!
GeneralRe: My vote of 3 [modified] Pin
taras_b26-Oct-10 2:39
taras_b26-Oct-10 2:39 
GeneralGood article Pin
clew_bel25-Oct-10 21:36
clew_bel25-Oct-10 21:36 

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.