Introduction
The HashSet<T>
class in C# is a collection that contains unique elements and provides high-performance set operations. It is part of the System.Collections.Generic
namespace and is useful for operations where uniqueness of elements is important and set-based operations like union, intersection, and difference are required.
Key Features of HashSet
- Unique Elements: Ensures that all elements in the collection are unique.
- High Performance: Offers O(1) time complexity for add, remove, and contains operations.
- Set Operations: Supports operations like union, intersection, and difference.
- No Ordering: Does not maintain any particular order for elements.
Creating a HashSet
Declaration and Initialization
You can declare and initialize a HashSet<T>
in several ways:
Example
using System;
using System.Collections.Generic;
namespace HashSetExample
{
class Program
{
static void Main(string[] args)
{
// Creating an empty HashSet
HashSet<int> numbers = new HashSet<int>();
// Creating a HashSet with initial elements
HashSet<string> fruits = new HashSet<string> { "Apple", "Banana", "Cherry" };
// Adding elements to the HashSet
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Adding duplicate elements (will not be added)
numbers.Add(1);
// Displaying elements
Console.WriteLine("Numbers: " + string.Join(", ", numbers));
Console.WriteLine("Fruits: " + string.Join(", ", fruits));
}
}
}
Output
Numbers: 1, 2, 3
Fruits: Apple, Banana, Cherry
Common Operations on HashSet
Adding Elements
- Add: Adds an element to the
HashSet
. Returnstrue
if the element is successfully added;false
if the element is already present.
bool isAdded = numbers.Add(4); // true
bool isDuplicateAdded = numbers.Add(2); // false
Removing Elements
- Remove: Removes the specified element from the
HashSet
. Returnstrue
if the element is successfully removed;false
otherwise.
bool isRemoved = numbers.Remove(2); // true
- RemoveWhere: Removes all elements that match the conditions defined by the specified predicate.
numbers.RemoveWhere(n => n > 3);
- Clear: Removes all elements from the
HashSet
.
numbers.Clear();
Accessing Elements
- Contains: Checks if the
HashSet
contains the specified element. Returnstrue
if the element is found;false
otherwise.
bool hasApple = fruits.Contains("Apple"); // true
Iterating Through a HashSet
You can iterate through a HashSet
using a foreach
loop.
Example
foreach (int number in numbers)
{
Console.WriteLine(number);
}
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Set Operations
- UnionWith: Modifies the current
HashSet
to contain all elements that are present in either the currentHashSet
or the specified collection.
HashSet<int> otherNumbers = new HashSet<int> { 3, 4, 5 };
numbers.UnionWith(otherNumbers);
- IntersectWith: Modifies the current
HashSet
to contain only elements that are present in both the currentHashSet
and the specified collection.
numbers.IntersectWith(otherNumbers);
- ExceptWith: Removes all elements in the specified collection from the current
HashSet
.
numbers.ExceptWith(otherNumbers);
- SymmetricExceptWith: Modifies the current
HashSet
to contain only elements that are present in either the currentHashSet
or the specified collection, but not both.
numbers.SymmetricExceptWith(otherNumbers);
Practical Example
Let’s create a practical example where we use a HashSet<T>
to manage a collection of unique student IDs.
Example
using System;
using System.Collections.Generic;
namespace StudentHashSetExample
{
class Program
{
static void Main(string[] args)
{
HashSet<int> studentIDs = new HashSet<int> { 101, 102, 103 };
// Adding new student IDs
studentIDs.Add(104);
studentIDs.Add(105);
// Attempting to add a duplicate student ID
bool isAdded = studentIDs.Add(101); // false
// Removing a student ID
studentIDs.Remove(102);
// Displaying all student IDs
Console.WriteLine("Student IDs:");
foreach (int id in studentIDs)
{
Console.WriteLine(id);
}
// Checking if a student ID exists
bool hasStudentID = studentIDs.Contains(103); // true
Console.WriteLine("Contains student ID 103: " + hasStudentID);
}
}
}
Output
Student IDs:
101
103
104
105
Contains student ID 103: True
Conclusion
The HashSet<T>
class in C# provides a high-performance, unique collection of elements with set operations like union, intersection, and difference. It is ideal for scenarios where you need to ensure the uniqueness of elements and perform set-based operations efficiently. Understanding how to use HashSet<T>
effectively can help you manage collections of unique data in your applications.