When dealing with collections in C#, you often find yourself in a situation where you want to store only unique elements – no duplicates. That's where HashSet<T> comes into play. In this article, we'll see what HashSet is, how it functions, and why you should use it.
HashSet: When dealing with collections in C#, you often find yourself in a situation where you want to store only unique elements – no duplicates. That's where HashSet<T> comes into play. In this article, we'll see what HashSet is, how it functions, and why you should use it.
Note:
- No duplicate elements
- Unordered collection
- Fast lookups, additions, and removals
- Built-in set operations (union, intersection, etc.)
- Duplicate values are automatically ignored
Basic Syntax:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<string> names= new HashSet<string>();
names.Add("Riya");
names.Add("Mohan");
names.Add("Sohan");
names.Add("Riya"); // Duplicate, will be ignored
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Note: The order may vary because HashSet is unordered.
Common operations:
1. Add Elements
2. Check if an Element Exists
bool hasName = names.Contains("Riya"); // true
3. Remove an Element
4. Count Elements
Set Operations
HashSet<T> supports several powerful set-based operations.
1. Union
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.UnionWith(set2);
// set1 = {1, 2, 3, 4, 5}
2. Intersection
set1.IntersectWith(set2);
// set1 = {3}
3. Difference
set1.ExceptWith(set2);
// set1 now only contains elements in set1 but not in set2
When to Use HashSet
Use a HashSet when:
- You need to ensure all elements are unique.
- You want fast membership testing (e.g., Contains()).
- You need to perform set operations like union, intersection, etc.
Limitations
- Unordered: If you need elements in a specific order, consider using SortedSet<T> or List<T>.
- No duplicates:If duplicates are allowed, use List<T> instead.
- Not thread-safe: Use ConcurrentDictionary or appropriate locking for multi-threaded scenarios.