EN
C# / .NET - add items to HashSet
0
points
In this article, we would like to show you how to add items to HashSet in C#.
Quick solution:
HashSet<string> myHashset = new HashSet<string>();
myHashset.Add("A");
Practical example
In this example, we add three elements to myHashset using Add() method.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
HashSet<string> myHashset = new HashSet<string>();
myHashset.Add("A");
myHashset.Add("B");
myHashset.Add("C");
foreach (string item in myHashset)
Console.WriteLine(item);
}
}
Output:
A
B
C
2. Add items on creation
In this example, we present how to add items while creating HashSet.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
HashSet<string> myHashset = new HashSet<string> { "A", "B", "C" };
foreach (string item in myHashset)
Console.WriteLine(item);
}
}
Output:
A
B
C