The HashSet<T> class in C# is part of the System.Collections.Generic namespace and provides an unordered collection of unique elements.
Unlike lists, a HashSet does not allow duplicate values, making it ideal when you need to store a collection of items without duplicates.
Hash sets provide fast insertion, deletion, and lookup operations, often with an average time complexity of O(1).
In this tutorial, we’ll cover:
1. Creating a HashSet<T>
To create a HashSet<T>, include the System.Collections.Generic namespace. T is the type parameter representing the type of elements in the hash set, such as int, string, or a custom class.
using System; using System.Collections.Generic; class Program { static void Main() { // Create an empty hash set of integers HashSet<int> numbers = new HashSet<int>(); // Create a hash set of strings with initial values HashSet<string> names = new HashSet<string> { "Alice", "Bob", "Charlie" }; Console.WriteLine("Initial names in hash set:"); foreach (string name in names) { Console.WriteLine(name); } } }
Output:
Initial names in hash set: Alice Bob Charlie
In this example:
- HashSet<int> numbers = new HashSet<int>(); creates an empty hash set of integers.
- HashSet<string> names = new HashSet<string> { “Alice”, “Bob”, “Charlie” }; initializes a hash set of strings with values.
2. Adding Elements to a Hash Set
You can add elements to a hash set using the Add method. Since HashSet<T> only stores unique elements, duplicate values are automatically ignored.
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> numbers = new HashSet<int>(); // Adding elements numbers.Add(10); numbers.Add(20); numbers.Add(30); numbers.Add(10); // Duplicate, will not be added Console.WriteLine("Numbers in hash set:"); foreach (int number in numbers) { Console.WriteLine(number); } } }
Output:
Numbers in hash set: 10 20 30
In this example:
- Add(10) tries to add 10 twice, but only one instance is stored because HashSet<T> does not allow duplicates.
3. Removing Elements
You can remove elements from a hash set using Remove or Clear.
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> numbers = new HashSet<int> { 10, 20, 30, 40 }; // Remove a specific element numbers.Remove(20); // Clear all elements from the hash set numbers.Clear(); Console.WriteLine("Numbers in hash set after clearing:"); foreach (int number in numbers) { Console.WriteLine(number); // No output since the set is empty } } }
Output:
Numbers in hash set after clearing:
In this example:
- Remove(20) removes the element 20.
- Clear() removes all elements from the hash set.
4. Checking for Elements and Set Operations
The Contains method checks if an element is present in the set. Additionally, HashSet<T> provides set operations like union, intersection, and difference.
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> setA = new HashSet<int> { 1, 2, 3, 4 }; HashSet<int> setB = new HashSet<int> { 3, 4, 5, 6 }; // Check for a specific element Console.WriteLine("setA contains 3: " + setA.Contains(3)); // Union of setA and setB setA.UnionWith(setB); Console.WriteLine("Union of setA and setB:"); foreach (int number in setA) { Console.WriteLine(number); } // Reset setA and setB setA = new HashSet<int> { 1, 2, 3, 4 }; setB = new HashSet<int> { 3, 4, 5, 6 }; // Intersection of setA and setB setA.IntersectWith(setB); Console.WriteLine("Intersection of setA and setB:"); foreach (int number in setA) { Console.WriteLine(number); } // Reset setA and setB setA = new HashSet<int> { 1, 2, 3, 4 }; setB = new HashSet<int> { 3, 4, 5, 6 }; // Difference of setA and setB (elements in setA but not in setB) setA.ExceptWith(setB); Console.WriteLine("Difference of setA and setB:"); foreach (int number in setA) { Console.WriteLine(number); } } }
Output:
setA contains 3: True Union of setA and setB: 1 2 3 4 5 6 Intersection of setA and setB: 3 4 Difference of setA and setB: 1 2
In this example:
- UnionWith(setB) adds elements from setB to setA, resulting in the union.
- IntersectWith(setB) retains only elements that exist in both sets.
- ExceptWith(setB) removes elements from setA that also exist in setB.
5. Commonly Used Methods
Here are some additional methods for working with HashSet<T>:
- Count: Gets the number of elements in the hash set.
- IsSubsetOf: Checks if the current set is a subset of another set.
- IsSupersetOf: Checks if the current set is a superset of another set.
- ToArray: Converts the hash set to an array.
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> setA = new HashSet<int> { 1, 2, 3, 4, 5 }; HashSet<int> setB = new HashSet<int> { 2, 3 }; // Count the elements Console.WriteLine("Count of setA: " + setA.Count); // Check if setB is a subset of setA Console.WriteLine("setB is a subset of setA: " + setB.IsSubsetOf(setA)); // Check if setA is a superset of setB Console.WriteLine("setA is a superset of setB: " + setA.IsSupersetOf(setB)); // Convert to array int[] array = setA.ToArray(); Console.WriteLine("Array from setA:"); foreach (int number in array) { Console.WriteLine(number); } } }
Output:
Count of setA: 5 setB is a subset of setA: True setA is a superset of setB: True Array from setA: 1 2 3 4 5
6. Iterating Through a HashSet<T>
You can iterate through a HashSet<T> using a foreach loop. Since HashSet<T> does not maintain any particular order, the elements may appear in any order.
using System; using System.Collections.Generic; class Program { static void Main() { HashSet<string> colors = new HashSet<string> { "Red", "Green", "Blue" }; // Using foreach loop Console.WriteLine("Colors in hash set:"); foreach (string color in colors) { Console.WriteLine(color); } } }
Output:
Colors in hash set: Red Green Blue
In this example:
- We iterate through the HashSet<string> called colors and print each color. The output order may vary because HashSet<T> does not guarantee element order.
Summary
In this tutorial, we covered the HashSet<T> class in C# and demonstrated its features:
- Creating a HashSet<T>: Initializing hash sets with or without initial values.
- Adding Elements: Using Add to add unique items.
- Removing Elements: Using Remove and Clear.
- Checking for Elements and Set Operations: Using Contains, UnionWith, IntersectWith, and ExceptWith.
- Commonly Used Methods: Methods like Count, IsSubsetOf, IsSupersetOf, and ToArray.
- Iterating Through a HashSet: Using foreach to iterate through all elements.
HashSet<T> is ideal when you need a fast, unique collection of items without duplicates, and it provides powerful set operations for tasks like finding unions and intersections.