HashSet is implemented with a hashtable that stores just keys;
Here's the definition for HashSet:
public class HashSet : ICollection, IEnumerable, IEnumerable
{
// Constructors public HashSet();
public HashSet (IEnumerable collection);
public HashSet (IEqualityComparer comparer);
public HashSet (IEnumerable collection, IEqualityComparer comparer);
// Testing for membership
public bool Contains (T item);
// Adding / removing
public bool Add (T item);
public bool Remove (T item);
public int RemoveWhere (Predicate match);
public void Clear();
// Set operations - destructive
public void UnionWith (IEnumerable other);
// Adds
public void IntersectWith (IEnumerable other);
// Removes
public void ExceptWith (IEnumerable other);
// Removes
public void SymmetricExceptWith (IEnumerable other); // Removes
// Set operations - bool
public bool IsSubsetOf (IEnumerable other);
public bool IsProperSubsetOf (IEnumerable other);
public bool IsSupersetOf (IEnumerable other);
public bool IsProperSupersetOf (IEnumerable other);
public bool Overlaps (IEnumerable other);
public bool SetEquals (IEnumerable other);
// Other
public int Count { get; }
public IEqualityComparer Comparer { get; }
public void CopyTo (T[] array);
public void CopyTo (T[] array, int arrayIndex);
public void CopyTo (T[] array, int arrayIndex, int count);
public void TrimExcess();
public static IEqualityComparer> CreateSetComparer();
}
SortedSet is implemented with a red/black tree.
The following constructs a HashSet from an existing collection, tests for membership, and then enumerates the collection.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Sample
{
public static void Main()
{
var letters = new HashSet("rntsoft.com tutorial and demo");
Console.WriteLine(letters.Contains('t')); // true
Console.WriteLine(letters.Contains('j')); // false
foreach (char c in letters)
Console.Write (c);
}
}
The output:
True
True
rntsoft.cm uilde
We can pass a string into HashSet's constructor because string implements IEnumerable.