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