CSharp - SortedSet<T> Type

Introduction

SortedSet<T> is generic collection with the following features:

  • Contains methods execute quickly using a hash-based lookup.
  • Ignore duplicate elements silently during adding operation.
  • Cannot access an element by position.

SortedSet<T> keeps elements in order whereas HashSet<T> does not.

SortedSet<T> is implemented with a red/black tree.

SortedSet<T> implements ICollection<T> and offers methods such as Contains, Add, and Remove.

SortedSet<T> has a predicate-based removal method called RemoveWhere.

SortedSet<T> offers all the members of HashSet<T>, plus the following:

public virtual SortedSet<T> GetViewBetween (T lowerValue, T upperValue)
public IEnumerable<T> Reverse()
public T Min { get; }
public T Max { get; }

SortedSet<T> accepts an optional IComparer<T> in its constructor.

The following code loads letters into a SortedSet<char>:

Demo

using System;
using System.Collections.Generic;
class MainClass/*from  w  w w. j a  va 2 s.c  o  m*/
{
   public static void Main(string[] args)
   {
      var letters = new SortedSet<char> ("this is a test");
      foreach (char c in letters) 
         Console.Write (c);
   }
}

Result

With SortedSet<T> we can get the value within a range:

Demo

using System;
using System.Collections.Generic;
class MainClass/*from w ww.j  a v a  2 s.c o m*/
{
   public static void Main(string[] args)
   {
      var letters = new SortedSet<char> ("this is a test");
      foreach (char c in letters) 
         Console.Write (c);

      foreach (char c in letters.GetViewBetween ('f', 'j'))
       Console.Write (c);                                 
   }
}

Result