Introduction
HashSet is an unordered collection of elements and a generic collection type. The HashSet supports the implementation of sets and uses the hash table for storage. The HashSet is available in the System.Collections.Generic namespace. It doesn’t allow duplicate values and can accept only one null value in the collection. The HashSet class implements the ICollection, IReadOnlyCollection, ISet, IEnumerable, IEnumerable, ISerializable interfaces, and IDeserializationCallback. The elements in a HashSet cannot be sorted because it is an unordered collection, and the order of elements is not defined. The HashSet increases dynamically as we add elements because the memory is allocated dynamically and doesn’t have any fixed size. The HashSet also supports set operations like intersection, union, and difference, along with creating, inserting and removing the elements. Let’s learn more about HashSet through the following example.
Must Read IEnumerable vs IQueryable, singleton design pattern in c#
You can also read about the - hash function in data structure
HashSet
using System;
using System.Collections.Generic;
class HashSetExample {
public static void Main()
{
HashSet<string> hashset1 = new HashSet<string>();
hashset1.Add("Banana");
hashset1.Add("Mango");
hashset1.Add("Apple");
hashset1.Add("Kiwi");
Console.WriteLine("Elements of HashSet:");
foreach(var value in hashset1)
{
Console.WriteLine(value);
}
hashset1.Remove("Mango");
Console.WriteLine("Elements of HashSet after removing an element:”);
foreach(var value in hashset1)
{
Console.WriteLine(value);
}
}
}
Output
Elements of HashSet:
Banana
Mango
Apple
Kiwi
Elements of HashSet after removing and element:
Banana
Apple
Kiwi
We created a string HashSet using the HashSet in Generic collection in System in the above code. We can add elements to the HashSet using the add() method and remove any element using the Remove() method as shown in the code. The output after and before removing the element is as shown above.