บทความนี้สาธิตวิธีตรวจสอบว่า HashSet<T> เป็น proper subset (ซับเซตที่เหมือนกันไม่ได้) ของคอลเลกชันที่ระบุ โดยใช้เมธอด IsProperSubsetOf() ใน C#
คืออะไร Proper Subset?
เซต A เป็น proper subset ของเซต B หาก:
- สมาชิกทุกตัวของ A อยู่ใน B (A ⊆ B)
- A ไม่เท่ากับ B — B มีสมาชิกเพิ่มเติมอย่างน้อยหนึ่งตัว
ตัวอย่างที่ 1: HashSet1 เป็น proper subset ของ HashSet2
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet<int> set1 = new HashSet<int>();
set1.Add(70);
set1.Add(100);
set1.Add(125);
set1.Add(150);
Console.WriteLine("Elements in HashSet1");
foreach (int val in set1)
{
Console.WriteLine(val);
}
HashSet<int> set2 = new HashSet<int>();
set2.Add(30);
set2.Add(60);
set2.Add(70);
set2.Add(80);
set2.Add(100);
set2.Add(125);
set2.Add(150);
set2.Add(200);
Console.WriteLine("Elements in HashSet2");
foreach (int val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("Is set1 a proper subset of set2? " + set1.IsProperSubsetOf(set2));
}
}
ผลลัพธ์
Elements in HashSet1 70 100 125 150 Elements in HashSet2 30 60 70 80 100 125 150 200 Is set1 a proper subset of set2? True
ตัวอย่างที่ 2: HashSet1 ไม่ใช่ subset ของ HashSet2 (มีสมาชิกที่ไม่มีใน set2)
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet<int> set1 = new HashSet<int>();
set1.Add(10);
set1.Add(20);
Console.WriteLine("Elements in HashSet1");
foreach (int val in set1)
{
Console.WriteLine(val);
}
HashSet<int> set2 = new HashSet<int>();
set2.Add(30);
set2.Add(60);
set2.Add(70);
set2.Add(80);
set2.Add(100);
set2.Add(125);
set2.Add(150);
set2.Add(200);
Console.WriteLine("Elements in HashSet2");
foreach (int val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("Is set1 a proper subset of set2? " + set1.IsProperSubsetOf(set2));
}
}
ผลลัพธ์
Elements in HashSet1 10 20 Elements in HashSet2 30 60 70 80 100 125 150 200 Is set1 a proper subset of set2? False
สรุป
- ใช้
IsProperSubsetOf(IEnumerable<T> other)เพื่อตรวจสอบ proper subset - คืนค่า
trueก็ต่อเมื่อสมาชิกทุกตัวของเซตปัจจุบันอยู่ใน other และ other มีสมาชิกเพิ่มเติมอย่างน้อยหนึ่งตัว - หากสองเซตมีสมาชิกเหมือนกันทุกตัว (equal sets) จะคืนค่า
false - HashSet ใช้ hash table ด้านใน —
Contains,Add,Removeมี complexity O(1) เฉลี่ย - ต่างจาก SortedSet: HashSet ไม่จัดเรียงลำดับ และเร็วกว่าสำหรับการค้นหา/เพิ่ม/ลบ
ตารางเปรียบเทียบเมธอดเซต (HashSet และ SortedSet เหมือนกัน)
| เมธอด | ความหมาย | คืนค่า true เมื่อ |
|---|---|---|
| IsSubsetOf | เป็น subset (รวม equal) | สมาชิกทุกตัวอยู่ใน other |
| IsProperSubsetOf | เป็น proper subset | เป็น subset และไม่เท่ากับ other |
| IsSupersetOf | เป็น superset (รวม equal) | มีสมาชิกครบทุกตัวของ other |
| IsProperSupersetOf | เป็น proper superset | เป็น superset และไม่เท่ากับ other |
| SetEquals | เท่ากัน (สมาชิกเหมือนกันทุกตัว) | สองเซตมีสมาชิกเหมือนกันทุกตัว |
| Overlaps | มีสมาชิกร่วมกันอย่างน้อย 1 ตัว | Intersection ≠ ∅ |