CSharp - HashSet<T> Type

Introduction

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.

Demo

using System;
using System.Collections.Generic;
class MainClass//from w w  w. j  av  a 2 s .c  o  m
{
   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);

   }
}

Result