มาดูตัวอย่างกันเพื่อรับ Union of two HashSet
ตัวอย่าง
using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<int> set1 = new HashSet<int>(); set1.Add(100); set1.Add(200); set1.Add(300); set1.Add(400); set1.Add(500); set1.Add(600); Console.WriteLine("HashSet1 elements..."); foreach(int ele in set1){ Console.WriteLine(ele); } HashSet<int> set2 = new HashSet<int>(); set2.Add(100); set2.Add(200); set2.Add(300); set2.Add(400); set2.Add(500); set2.Add(600); Console.WriteLine("HashSet2 elements..."); foreach(int ele in set2){ Console.WriteLine(ele); } Console.WriteLine("Union..."); set1.UnionWith(set2); foreach(int ele in set1){ Console.WriteLine(ele); } } }
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
HashSet1 elements... 100 200 300 400 500 600 HashSet2 elements... 100 200 300 400 500 600 Union... 100 200 300 400 500 600
ตัวอย่าง
เรามาดูตัวอย่างอื่นกัน −
using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<int> set1 = new HashSet<int>(); set1.Add(100); set1.Add(200); set1.Add(300); set1.Add(400); set1.Add(500); set1.Add(600); Console.WriteLine("HashSet1 elements..."); foreach(int ele in set1){ Console.WriteLine(ele); } HashSet<int> set2 = new HashSet<int>(); set2.Add(100); set2.Add(250); set2.Add(300); Console.WriteLine("HashSet2 elements..."); foreach(int ele in set2){ Console.WriteLine(ele); } Console.WriteLine("Union..."); set1.UnionWith(set2); foreach(int ele in set1){ Console.WriteLine(ele); } } }
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
HashSet1 elements... 100 200 300 400 500 600 HashSet2 elements... 100 250 300 Union... 100 200 300 400 500 600 250