The C# HashSet class enables storage, removal, and viewing of elements without allowing duplicates. Opt for the HashSet class when you need to maintain a collection of distinct elements. This class is located within the System.Collections.Generic namespace.
C# HashSet__PRESERVE_5__ example
Let's examine a sample HashSet<T> class that is generic in nature, storing elements through the Add function and iterating over elements using a for-each loop.
Example
using System;
using System.Collections.Generic;
public class HashSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new HashSet<string>();
names.Add("Sonoo");
names.Add("Ankit");
names.Add("Peter");
names.Add("Irfan");
names.Add("Ankit");//will not be added
// Iterate HashSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Output
Sonoo
Ankit
Peter
Irfan
C# HashSet__PRESERVE_7__ example 2
Let's explore an additional illustration of a generic HashSet<T> class that stores elements through a Collection initializer.
Example
using System;
using System.Collections.Generic;
public class HashSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new HashSet<string>(){"Sonoo", "Ankit", "Peter", "Irfan"};
// Iterate HashSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Output
Sonoo
Ankit
Peter
Irfan