Mega Code Archive

 
Categories / C# Book / 03 Collections
 

0360 HashSet

HashSet<T> is implemented with a hashtable that stores just keys; Here's the definition for HashSet<T>: public class HashSet<T> : ICollection<T>, IEnumerable<T>, IEnumerable { // Constructors public HashSet(); public HashSet (IEnumerable<T> collection); public HashSet (IEqualityComparer<T> comparer); public HashSet (IEnumerable<T> collection, IEqualityComparer<T> 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<T> match); public void Clear(); // Set operations - destructive public void UnionWith (IEnumerable<T> other); // Adds public void IntersectWith (IEnumerable<T> other); // Removes public void ExceptWith (IEnumerable<T> other); // Removes public void SymmetricExceptWith (IEnumerable<T> other); // Removes // Set operations - bool public bool IsSubsetOf (IEnumerable<T> other); public bool IsProperSubsetOf (IEnumerable<T> other); public bool IsSupersetOf (IEnumerable<T> other); public bool IsProperSupersetOf (IEnumerable<T> other); public bool Overlaps (IEnumerable<T> other); public bool SetEquals (IEnumerable<T> other); // Other public int Count { get; } public IEqualityComparer<T> 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<HashSet<T>> CreateSetComparer(); } SortedSet<T> is implemented with a red/black tree. The following constructs a HashSet<char> 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<char>("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<char>'s constructor because string implements IEnumerable<char>.