What is HashSet in C#?
A HashSet is a collection that stores only unique elements using a hash table, this is used to enable faster retrieval of elements compared to other collection types.
C# Program to show the use of HashSet in C#:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a new HashSet of strings
HashSet<string> cars = new HashSet<string>();
// Add elements to the HashSet
cars.Add("Audi");
cars.Add("Ford");
cars.Add("Mazda");
cars.Add("Tesla");
cars.Add("Mazda");// Duplicate element, will not be added
// Display the elements in the HashSet
Console.WriteLine("Cars in the HashSet:");
foreach (var car in cars)
{
Console.WriteLine(car);
}
// Check if an element exists in the HashSet
string carToCheck = "Ford";
if (cars.Contains(carToCheck))
{
Console.WriteLine($"\n{carToCheck} is in the HashSet.");
}
else
{
Console.WriteLine($"\n{carToCheck} is not in the HashSet.");
}
// Remove an element from the HashSet
cars.Remove("Tesla");
Console.WriteLine("\nAfter removing 'Tesla':");
foreach (var car in cars)
{
Console.WriteLine(car);
}
// Get the number of elements in the HashSet
Console.WriteLine($"\nNumber of elements in the HashSet: {cars.Count}");
// Clear all elements from the HashSet
cars.Clear();
Console.WriteLine($"\nNumber of elements in the HashSet after clearing: {cars.Count}");
Console.ReadKey();
}
}
We have the below operations in the above program,
- Creating a HashSet: The
HashSet<string>
namedcars
is created to store a collection of unique strings. - Adding Elements: Elements are added to the
HashSet
using theAdd
method. If an element already exists, it will not be added again. - Displaying Elements: The elements in the
HashSet
are displayed using aforeach
loop. - Checking for Existence: The
Contains
method checks if a specific element exists in theHashSet
. - Removing Elements: The
Remove
method removes an element from theHashSet
. - Getting the Count: The
Count
property returns the number of elements in theHashSet
. - Clearing the HashSet: The
Clear
method removes all elements from theHashSet
.
Output:
Cars in the HashSet:
Audi
Ford
Mazda
Tesla
Ford is in the HashSet.
After removing 'Tesla':
Audi
Ford
Mazda
Number of elements in the HashSet: 3
Number of elements in the HashSet after clearing: 0
Comments (0)