EN
C# / .NET - add List into HashSet
0
points
In this article, we would like to show you how to add List into HashSet in C#.
Quick solution:
List<string> letters = new List<string> { "A", "B", "C" };
HashSet<string> alphabet = new HashSet<string>(letters);
1. Add ArrayList on HashSet creation
In this example, we add existing letters
List to a new alphabet
HashSet in the constructor.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> letters = new List<string> { "A", "B", "C" };
HashSet<string> alphabet = new HashSet<string>(letters);
foreach (string letter in alphabet)
Console.WriteLine(letter);
}
}
Output:
A
B
C
2. Add List to the existing HashSet
In this example, we add existing letters
List to the existing alphabet
HashSet using UnionWith()
method.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> letters = new List<string> { "A", "B", "C" };
HashSet<string> alphabet = new HashSet<string>();
alphabet.UnionWith(letters);
foreach (string letter in alphabet)
Console.WriteLine(letter);
}
}
Output:
A
B
C