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
热门推荐
10 2026猪年祝福语简短语
11 七一祝福语明信片文案简短
12 儿子31岁祝福语简短
13 求助短信生日祝福语简短
14 白羊生日祝福语 简短独特
15 娘家除夕祝福语大全简短
16 新婚红包祝福语简短男
17 初八的祝福语简短
18 亲戚送行祝福语简短精辟