ใช้เมธอด UnionWith ใน C # เพื่อรับการรวมของ lement ที่ไม่ซ้ำจากสองคอลเล็กชัน
สมมติว่าต่อไปนี้คือพจนานุกรมของเรา -
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