In C#, a HashSet is a powerful and efficient collection type designed for storing unique elements. It provides fast lookup, insertion, and removal operations, making it ideal for scenarios where you need to maintain a set of distinct items.
ISet<T>
interfaceTo use a HashSet in C#, you first need to include the System.Collections.Generic
namespace. Here's a basic example of creating and using a HashSet:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<string> fruits = new HashSet<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");
fruits.Add("Apple"); // Duplicate, won't be added
Console.WriteLine($"Count: {fruits.Count}"); // Output: Count: 3
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}
In this example, we create a HashSet of strings and add some fruit names. Notice that the duplicate "Apple" is not added, maintaining the uniqueness of elements in the set.
HashSet provides several useful methods for set operations:
bool containsBanana = fruits.Contains("Banana"); // Returns true
bool removed = fruits.Remove("Cherry"); // Returns true if Cherry was in the set
HashSet<string> set1 = new HashSet<string> { "A", "B", "C" };
HashSet<string> set2 = new HashSet<string> { "B", "C", "D" };
set1.UnionWith(set2); // set1 now contains { "A", "B", "C", "D" }
set1.IntersectWith(set2); // set1 now contains { "B", "C" }
set1.ExceptWith(set2); // set1 now contains { "A" }
HashSet is optimized for fast lookups and uniqueness checks. It's particularly useful when you need to:
However, keep in mind that HashSet does not maintain insertion order. If order is important, consider using a C# List in combination with additional logic to ensure uniqueness.
Feature | HashSet | List | Dictionary |
---|---|---|---|
Uniqueness | Enforced | Not enforced | Keys unique |
Lookup speed | O(1) average | O(n) | O(1) average |
Ordered | No | Yes | No |
C# HashSet is a versatile and efficient collection for managing unique elements. Its fast operations and set-based functionality make it an excellent choice for many scenarios in C# programming. By understanding its strengths and use cases, you can leverage HashSet to write more efficient and cleaner code.
For more advanced collection types in C#, you might want to explore C# Dictionaries or C# Queue and Stack.