ภาพรวม
HashSet<T> ใน namespace System.Collections.Generic เป็นเซตที่เก็บค่าไม่ซ้ำ โดยใช้ตารางแฮช (hash table) ให้การค้นหา เพิ่ม ลบ O(1) เฉลี่ย เมธอด UnionWith() รวมองค์ประกอบจากเซตอื่นเข้าไป (union operation) แบบ in-place
ตัวอย่างที่ 1: ยูเนียนของเซตเหมือนกัน
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
ตัวอย่างที่ 2: ยูเนียนของเซตที่ต่างกันบางส่วน
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
คำอธิบายเพิ่มเติม
UnionWith()แก้ไขเซตต้นทาง (set1) โดยตรง ไม่คืนค่าเซตใหม่- พารามิเตอร์รับ
IEnumerable<T>ใดๆ ก็ได้ (List, Array, SortedSet, อื่นๆ) - HashSet ไม่รักษาลำดับ การวนลูปอาจได้ลำดับต่างจากการเพิ่ม
- ซับซ้อนเวลา O(m) โดย m = จำนวนองค์ประกอบในคอลเลกชันที่ส่งเข้า (สมมติ hash distribution ดี)
- เมธอดเซตอื่นๆ:
IntersectWith()( 교집합),ExceptWith()(차집합),SymmetricExceptWith()(대칭 차집합)