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:
xxxxxxxxxx
1
HashSet<string> myHashset = new HashSet<string>();
2
3
myHashset.Add("A");
In this example, we add three elements to myHashset
using Add()
method.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
HashSet<string> myHashset = new HashSet<string>();
9
10
myHashset.Add("A");
11
myHashset.Add("B");
12
myHashset.Add("C");
13
14
foreach (string item in myHashset)
15
Console.WriteLine(item);
16
}
17
}
Output:
xxxxxxxxxx
1
A
2
B
3
C
In this example, we present how to add items while creating HashSet.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
HashSet<string> myHashset = new HashSet<string> { "A", "B", "C" };
9
10
foreach (string item in myHashset)
11
Console.WriteLine(item);
12
}
13
}
Output:
xxxxxxxxxx
1
A
2
B
3
C