C# 中的 UnionWith 方法

csharpprogrammingserver side programming更新于 2025/9/23 1:22:17

使用 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

相关文章