The world of .NET from a Connected Systems MVP & INETA Speaker

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 characters
            var letters = new SortedSet<char>("the quick brown fox");
            foreach (char c in letters) Console.Write(c);  // bcefhiknoqrtuwx
 
            // Get the letters between f and j
            foreach(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 sets
            letters.IntersectWith("aeiou");
            foreach(char c in letters) Console.Write(c);   // euio
 
            // Strip all vowels with ExceptWith
            var 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 other
            var letters3 = new SortedSet<char>("the quick brown fox");
            letters3.SymmetricExceptWith("the lazy brown fox");
            foreach(char c in letters3) Console.Write(c);   
        }
    }
}
 

» Similar Posts

  1. C# 4.0/BCL 4 Series:Dynamic Primitive Type Part 2
  2. Windows Workflow 101 or 2 Months with WF
  3. SOA: Making the Paradigm Shift Part 11 of N

» Trackbacks & Pingbacks

  1. Pingback from Markus Tamm » Blog Archive » Links 03.06.2010

Trackback link for this post:
http://samgentile.com/Web/trackback.ashx?id=1914

» Comments

    There are no comments. Kick things off by filling out the form below.

» Leave a Comment