EN
C# / .NET - merge two Lists into HashSet
0 points
In this article, we would like to show you how to merge two Lists into HashSet in C#.
Quick solution:
xxxxxxxxxx
1
List<string> list1 = new List<string> { "A", "B", "C" };
2
List<string> list2 = new List<string> { "D", "B", "C" };
3
4
HashSet<string> alphabet = new HashSet<string>(list1);
5
6
alphabet.UnionWith(list2);
In this example, we merge list1
and list2
Lists into alphabet
HashSet using UnionWith()
method.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
List<string> list1 = new List<string> { "A", "B", "C" };
9
List<string> list2 = new List<string> { "D", "B", "C" };
10
11
// initialize hashset with list1 on creation
12
HashSet<string> alphabet = new HashSet<string>(list1);
13
14
// add list2
15
alphabet.UnionWith(list2);
16
17
// print items
18
foreach (string item in alphabet)
19
Console.WriteLine(item);
20
}
21
}
Output:
xxxxxxxxxx
1
A
2
B
3
C
4
D
Note:
Merging two Lists into a HashSet removes duplicate elements.