Curriculum
HashSet is a class in C# that represents a collection of unique elements, where each element is distinct from all others. Here’s an example of using HashSet to store and manipulate a collection of strings:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Create a HashSet of strings
HashSet<string> names = new HashSet<string>();
// Add some names to the set
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
// Display the contents of the set
Console.WriteLine("Names in set:");
foreach (string name in names)
{
Console.WriteLine(name);
}
// Try to add a duplicate name to the set
if (!names.Add("Bob"))
{
Console.WriteLine("Bob is already in the set");
}
// Remove a name from the set
names.Remove("Charlie");
// Display the updated contents of the set
Console.WriteLine("Names in set after removing Charlie:");
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
In this example, we first create an empty HashSet<string> object called names. We then add some strings to the set using the Add method. We use a foreach loop to display the contents of the set.
Next, we try to add a duplicate name (“Bob”) to the set using the Add method. Since HashSet only allows unique elements, the Add method returns false and we display an error message.
We then use the Remove method to remove the name “Charlie” from the set. Finally, we use another foreach loop to display the updated contents of the set.
Here are some other useful methods provided by the HashSet class:
Count: Returns the number of elements in the set.Contains: Determines whether an element is in the set.UnionWith: Modifies the current set to include all elements from another collection.IntersectWith: Modifies the current set to contain only elements that are also in another collection.Clear: Removes all elements from the set.Here’s an example that demonstrates some of these methods:
// Create two sets of integers
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Combine the two sets
set1.UnionWith(set2);
// Display the contents of the combined set
Console.WriteLine("Combined set:");
foreach (int number in set1)
{
Console.WriteLine(number);
}
// Remove all elements that are not in both sets
set1.IntersectWith(set2);
// Display the contents of the intersected set
Console.WriteLine("Intersected set:");
foreach (int number in set1)
{
Console.WriteLine(number);
}
It’s important to note that HashSet provides many other useful properties and methods for working with sets, such as SymmetricExceptWith to modify the current set to contain only elements that are not also in another collection, IsSubsetOf to determine whether the current set is a subset of another collection, and GetEnumerator to get an enumerator that iterates through the set.