EN
C# / .NET - remove items from HashSet
0
points
In this article, we would like to show you how to remove items from HashSet in C#.
Quick solution:
HashSet<string> myHashset = new HashSet<string> { "A", "B", "C" };
myHashset.Remove("A");
Practical example
In this example, we use Remove() method to delete selected item from the myHashset.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
HashSet<string> myHashset = new HashSet<string> { "A", "B", "C" };
myHashset.Remove("A");
foreach (string item in myHashset)
Console.WriteLine(item);
}
}
Output:
B
C
2. Remove all items
In this example, we use Clear() method to remove all items from myHashset.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
HashSet<string> myHashset = new HashSet<string> { "A", "B", "C" };
Console.WriteLine("Before:");
foreach (string item in myHashset)
Console.WriteLine(item);
myHashset.Clear(); // clear HashSet
Console.WriteLine("\nAfter:");
foreach (string item in myHashset)
Console.WriteLine(item);
}
}
Output:
Before:
A
B
C
After: