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

An Introduction to SortedSet Collection of .NET 4.0

0.00/5 (No votes)
26 Oct 2010 1  
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 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