C# 中的 UnionWith 方法
在 C# 中使用 UnionWith 方法可以获取两个集合的并集,即唯一元素。
假设以下是我们的词典 −
Dictionary < string, int > dict1 = new Dictionary < string, int > ();
dict1.Add("pencil", 1);
dict1.Add("pen", 2);
Dictionary < string, int > dict2 = new Dictionary < string, int > ();
dict2.Add("pen", 3);现在,使用 HashSet 和 UnionWith 获取并集 −
HashSet < string > hSet = new HashSet < string > (dict1.Keys); hSet.UnionWith(dict2.Keys);
以下是完整代码 −
示例
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
Dictionary < string, int > dict1 = new Dictionary < string, int > ();
dict1.Add("pencil", 1);
dict1.Add("pen", 2);
Dictionary < string, int > dict2 = new Dictionary < string, int > ();
dict2.Add("pen", 3);
HashSet < string > hSet = new HashSet <string > (dict1.Keys);
hSet.UnionWith(dict2.Keys);
Console.WriteLine("Merged Dictionary...");
foreach(string val in hSet) {
Console.WriteLine(val);
}
}
}输出
Merged Dictionary... pencil pen
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP