Sử dụng phương thức UnionWith trong C # để lấy kết hợp các khoản vay duy nhất từ hai tập hợp.
Giả sử sau đây là Từ điển của chúng tôi -
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); Bây giờ, hãy sử dụng HashSet và UnionWith để liên kết -
HashSet < string > hSet = new HashSet < string > (dict1.Keys); hSet.UnionWith(dict2.Keys);
Sau đây là mã hoàn chỉnh -
Ví dụ
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);
}
}
} Đầu ra
Merged Dictionary... pencil pen