![]() |
VOOZH | about |
A HashSet<T> is a collection of unique elements. It does not allow duplicates and does not maintain any particular order.
Example: The following example shows how to create a HashSet
Elements in the HashSet: 10 20 30
The HashSet class provides different ways to create a HashSet. Here we will use the HashSet() constructor to create an instance of the HashSet class that is empty and uses the default equality comparer for the set type.
Step 1: Include System.Collections.Generic namespace
using System.Collections.Generic;
Step 2: Create a HashSet using the HashSet class
HashSet<Type_of_hashset> Hashset_name = new HashSet<Type_of_hashset>();
o add elements to a HashSet, use the Add() method to add or we can also store elements in your HashSet using a collection initializer.
// Using Add method
set.Add(1);
set.Add(2);// Using Collection Initializer
HashSet<int> s = new HashSet<int>{1, 2, 3};
We generally use a foreach loop to iterate through the elements of a HashSet. Example:
Elements of set1: C C++ C# Java Ruby Elements of set2: 1 2 3
We can remove elements from a HashSet using three methods:
Example:
Elements (Before Removal): 5 Elements (After Removal): 4
The HashSet class also provides some methods that are used to perform different operations on sets and the methods are:
Example:
After Union: 1, 2, 3, 5, 4 After Intersection: 3, 5 After Difference: 3
Note: HashSet does not maintain any specific order of elements, so the output order may vary.