You can get the overview on what’s new in .NET FW BCL by reading my post .NET Framework 4 BCL. This post explains about one of the feature SortedSet. .NET Framework 4 adds a new collection to System.Collections.Generic, named Sorted Set<T>. It is like HashSet<T> collection of unique elements, but SortedSet<T> keeps the elements in sorted order.
The Collection is implemented using red-black tree datastructure. Compared to HashSet<T> provides lesser performance for insert,delete and lookup operations. Use this collection if you want to keep the elements in sorted order.
Example: You need to get the subset of elements in a particular range to use SortedSet<t>.
var setRange = new SortedSet<int>() {2,5,6,2,1,4,8 }; foreach(var i in setRange){ Console.Write(i); } //output: 124568
In above case integers are added to the set in no particular order. Note that 2 is added twice. The output we see that they are in sorted order and without 2. Like HashSet<T> SortedSet has add method which returns bool type and returns true when the item is added successfully to the list.
We can also get the Max and Min elements within set and get a subset of elements in particular range.
setRange.Min and setRange.Max var subSet = setRange.GetViewBetween(2,6);
The GetViewBetween method returns a view of the original set. Any changes made to the view will be reflected in the original.
Share this post : |