C# 4.0/BCL 4 Series:SortedSet<T> in Framework 4
This is part of a series. To add to 3.5's new HashSet<T>, there is now SortedSet<T> new in 4.0. Both have the following distinguishing features:
- Their Contains methods execute quickly using a hash-based lookup
- They do not store duplicate elements and silently ignore requests to add duplicates
- You cannot access an element by position
SortedSet<T> keeps elements in order, whereas HashSet<T> does not. HashSet<T> is implemented wuth a hashtable that just stores keys;SortedSet<T> is implemented with a red/black tree.
You can consult MSDN for the definition of HashSet but SortedSet<T> adds:
- public virtual SortedSet<T> GetViewBetween(T lowerValue, T upperValue)
- public IEnumerable<T> Reverse()
- public T Min( get; )
- public T Max( get; )
Let's see how to use some of SortedSet<T>:
using System;using System.Collections.Generic;namespace SortedSet{class Program{static void Main(string[] args){// Loading letters into a SortedSet<char> and// enumerating the charactersvar letters = new SortedSet<char>("the quick brown fox");foreach (char c in letters) Console.Write(c); // bcefhiknoqrtuwx// Get the letters between f and jforeach(char c in letters.GetViewBetween('f', 'j'))Console.WriteLine(c);// Destructive set operators modify the original collection// UnionWith adds all the elements in the 2nd set to the// original (excluding duplicates)// IntersectsWith removes all the elements that are not// in both setsletters.IntersectWith("aeiou");foreach(char c in letters) Console.Write(c); // euio// Strip all vowels with ExceptWithvar letters2 = new SortedSet<char>("aeiou");foreach(char c in letters2) Console.Write(c);// SymmmetricExcerptWith removes all but the elements// that are unique to one set or othervar letters3 = new SortedSet<char>("the quick brown fox");letters3.SymmetricExceptWith("the lazy brown fox");foreach(char c in letters3) Console.Write(c);}}}
Filed under: VS2010 and .NET Framework 4.0

Pingback from Markus Tamm » Blog Archive » Links 03.06.2010