Introduction
C# HashSet is an unordered collection that contains unique elements. The HashSet<T> class represents a hash set that is defined in the System.Collections.Generic namespace. .NET HashSet class provides several methods to add items, remove items, find and search items. The HashSet class also offers methods to compare two objects and supports operations such as union, intersection, subset, superset, overlap and symmetric differences.
Create Hashset<T>
Like any other object in .NET and C#, we use the new operator to create a HashSet object and pass a data type. The following code snippet creates two objects of int type data.
- HashSet<int> firstset = new HashSet<int>();
- HashSet<int> secondset = new HashSet<int>();
Add Items to HashSet
The Add method is used to insert items to a HashSet. The following code snippet adds items to both of the HashSet objects defined in the previous section.
- for (int i = 1; i < 10; i++) {
- firstset.Add(5 * i);
- }
- for (int j = 1; j < 10; j++) {
- secondset.Add(10 * j);
- }
Read HashSet Items
All collection objects in C# and .NET can be read using a foreach loop. The following code snippet reads both HashSet collections and prints their itesm to the console.
- namespace ConsoleApplication14 {
- class Program {
- static void Main(string[] args) {
- HashSet < int > firstset = new HashSet < int > ();
- HashSet < int > secondset = new HashSet < int > ();
- for (int i = 1; i <= 10; i++) {
- firstset.Add(5 * i);
- }
- for (int j = 1; j <= 10; j++) {
- secondset.Add(10 * j);
- }
- Console.WriteLine("The table of five(5) is:");
- foreach(int a in firstset) {
- Console.WriteLine(a);
- }
- Console.WriteLine("The table of Ten(10) is:");
- foreach(int b in secondset) {
- Console.WriteLine(b);
- }
- }
- }
- }
Here is the output.




Mahesh AllePosted Jul 29, 2019, 2:16 AM
Good Article. I want to know how this HashSet is different from others. I mean why we should we use HashSet apart from other collections. What features make HashSet as unique from others.
Pankajkumar PatelPosted Jul 29, 2019, 1:10 AM
Good article and thanks for sharing this
Bidyasagar MishraPosted Jul 28, 2019, 10:28 PM
Nice article
Murugappan MnPosted Aug 27, 2015, 3:33 AM
nice one.