CSharp - HashSet<T> Type


HashSet<T> is a 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.

HashSet<T> is implemented with a hashtable.

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

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

The following code creates a HashSet<char> from an existing collection.

Then it uses Contains method to check if the element is in.


using System;
using System.Collections.Generic;
class MainClass/*  w ww .  j  a va2s .c om*/
   public static void Main(string[] args)

     var letters = new HashSet<char> ("the quick brown fox this is atest ");

     Console.WriteLine (letters.Contains ('t'));      // true
     Console.WriteLine (letters.Contains ('j'));      // false

     foreach (char c in letters)
        Console.Write (c);