HashSet in C# with Example
In C#, HashSet<T> is a collection class within the System.Collections.Generic namespace that provides high-performance set operations. Unlike lists or arrays, HashSet<T> ensures that all elements are unique and offers fast lookups, making it particularly suitable for scenarios involving set-based operations like unions and intersections. This article provides an overview of HashSet<T>, its key features, and practical examples of its usage.
Key Features of HashSet<T>
- Unordered Collection: Elements are not stored in any specific order.
- Unique Elements: Each element is guaranteed to appear only once in the collection.
- High Performance: Offers average O(1) time complexity for lookup operations.
Common Operations
- Add(T item): Adds an element to the set if it is not already present.
- Contains(T item): Checks whether an element is in the set.
- Remove(T item): Removes a specified element from the set.
- UnionWith(IEnumerable<T> other): Combines the current set with another collection, keeping unique elements only.
- IntersectWith(IEnumerable<T> other): Retains only the elements that are also in another collection.
- ExceptWith(IEnumerable<T> other): Removes all elements from the current set that are present in another collection.
Example: Using HashSet<T> in C#
Here's an example that demonstrates how to use HashSet<T> for managing a collection of unique strings:
using System;
using System.Collections.Generic;
public class HashSetExample
{
public static void Main()
{
// Creating a new HashSet of strings
HashSet<string> uniqueFruits = new HashSet<string>();
// Adding elements to the HashSet
uniqueFruits.Add("Apple");
uniqueFruits.Add("Banana");
uniqueFruits.Add("Orange");
// Attempting to add a duplicate
if (!uniqueFruits.Add("Apple"))
{
Console.WriteLine("Apple is already in the HashSet.");
}
// Checking if an element exists
if (uniqueFruits.Contains("Orange"))
{
Console.WriteLine("Orange is in the HashSet.");
}
// Removing an element
uniqueFruits.Remove("Banana");
// Displaying all elements in the HashSet
Console.WriteLine("Current fruits in the HashSet:");
foreach (string fruit in uniqueFruits)
{
Console.WriteLine(fruit);
}
// Demonstrating set operations
HashSet<string> tropicalFruits = new HashSet<string> { "Banana", "Pineapple", "Mango", "Orange" };
// Union
uniqueFruits.UnionWith(tropicalFruits);
Console.WriteLine("After union with tropical fruits:");
foreach (string fruit in uniqueFruits)
{
Console.WriteLine(fruit);
}
// Intersection
HashSet<string> commonFruits = new HashSet<string>(uniqueFruits);
commonFruits.IntersectWith(tropicalFruits);
Console.WriteLine("Common fruits between the sets:");
foreach (string fruit in commonFruits)
{
Console.WriteLine(fruit);
}
}
}
Practical Applications of HashSet
- Duplicate Removal: Ideal for scenarios where duplicate items should be removed from a collection.
- Membership Testing: Quickly determine whether an element is part of a collection.
- Set Operations: Implement unions, intersections, and differences efficiently.
Conclusion
The HashSet<T> class in C# is a versatile tool for managing collections where uniqueness and high performance are crucial. With a clear understanding of its operations and use cases, developers can leverage it to build efficient and robust applications.