这篇文章将讨论如何在 C# 中合并两个 HashSet。
1.使用
HashSet<T>.UnionWith()
方法
合并内容的最短和最惯用的方法
HashSet<T>
具有另一个内容的对象
HashSet<T>
正在使用
HashSet<T>.UnionWith()
方法。它修改了
HashSet<T>
包含本身存在的所有元素以及指定 HashSet 中的元素(或任何其他
IEnumerable
一般来说)。它可用于将多个值添加到现有的
HashSet<T>
对象,如下图:
例如,以下代码将第二个集合中包含的所有元素与第一个集合中包含的元素合并。请注意,集合不允许重复元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using
System
;
using
System
.
Collections
.
Generic
;
public
class
Example
{
public
static
void
Main
(
)
{
HashSet
<
int
>
set1
=
new
HashSet
<
int
>
(
)
{
2
,
3
,
4
}
;
HashSet
<
int
>
set2
=
new
HashSet
<
int
>
(
)
{
4
,
5
,
6
}
;
set1
.
UnionWith
(
set2
)
;
Console
.
WriteLine
(
String
.
Join
(
", "
,
set1
)
)
;
// 2, 3, 4, 5, 6
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using
System
;
using
System
.
Collections
.
Generic
;
public
class
Example
{
public
static
void
Main
(
)
{
HashSet
<
int
>
set1
=
new
HashSet
<
int
>
(
)
{
2
,
3
,
4
}
;
HashSet
<
int
>
set2
=
new
HashSet
<
int
>
(
)
{
4
,
5
,
6
}
;
foreach
(
var
item
in
set2
)
{
set1
.
Add
(
item
)
;
}
Console
.
WriteLine
(
String
.
Join
(
", "
,
set1
)
)
;
// 2, 3, 4, 5, 6
}
}