บทความนี้สาธิตวิธีตรวจสอบว่า SortedSet<T> เป็น proper subset (ซับเซตที่เหมือนกันไม่ได้) ของคอลเลกชันที่ระบุ โดยใช้เมธอด IsProperSubsetOf() ใน C#
คืออะไร Proper Subset?
เซต A เป็น proper subset ของเซต B หาก:
- สมาชิกทุกตัวของ A อยู่ใน B (A ⊆ B)
- A ไม่เท่ากับ B — หมายความว่า B มีสมาชิกเพิ่มเติมอย่างน้อยหนึ่งตัวที่ไม่อยู่ใน A
ตัวอย่างที่ 1: SortedSet2 เป็น proper subset ของ SortedSet1
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet<int> set1 = new SortedSet<int>();
set1.Add(20);
set1.Add(40);
set1.Add(60);
set1.Add(80);
set1.Add(100);
set1.Add(120);
set1.Add(140);
Console.WriteLine("Elements in SortedSet1...");
foreach (int res in set1)
{
Console.WriteLine(res);
}
SortedSet<int> set2 = new SortedSet<int>();
set2.Add(20);
set2.Add(40);
set2.Add(60);
Console.WriteLine("Elements in SortedSet2...");
foreach (int res in set2)
{
Console.WriteLine(res);
}
Console.WriteLine("SortedSet2 is a proper subset of SortedSet1? = " + set2.IsProperSubsetOf(set1));
}
}
ผลลัพธ์
Elements in SortedSet1... 20 40 60 80 100 120 140 Elements in SortedSet2... 20 40 60 SortedSet2 is a proper subset of SortedSet1? = True
ตัวอย่างที่ 2: สองเซตมีสมาชิกเหมือนกันทุกตัว (ไม่ใช่ proper subset)
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet<int> set1 = new SortedSet<int>();
set1.Add(20);
set1.Add(40);
set1.Add(60);
Console.WriteLine("Elements in SortedSet1...");
foreach (int res in set1)
{
Console.WriteLine(res);
}
SortedSet<int> set2 = new SortedSet<int>();
set2.Add(20);
set2.Add(40);
set2.Add(60);
Console.WriteLine("Elements in SortedSet2...");
foreach (int res in set2)
{
Console.WriteLine(res);
}
Console.WriteLine("SortedSet2 is a proper subset of SortedSet1? = " + set2.IsProperSubsetOf(set1));
}
}
ผลลัพธ์
Elements in SortedSet1... 20 40 60 Elements in SortedSet2... 20 40 60 SortedSet2 is a proper subset of SortedSet1? = False
สรุป
- ใช้
IsProperSubsetOf(IEnumerable<T> other)เพื่อตรวจสอบ proper subset - คืนค่า
trueก็ต่อเมื่อสมาชิกทุกตัวของเซตปัจจุบันอยู่ใน other และ other มีสมาชิกเพิ่มเติมอย่างน้อยหนึ่งตัว - หากสองเซตมีสมาชิกเหมือนกันทุกตัว (equal sets) จะคืนค่า
false - SortedSet รับพารามิเตอร์เป็น
IEnumerable<T>ใช้กับ array, List, HashSet ได้ - Complexity: O(n log m) โดย n = จำนวนสมาชิกในเซตปัจจุบัน, m = จำนวนสมาชิกใน other
ตารางสรุปเมธอดเซต (ซ้ำเพื่อความสะดวก)
| เมธอด | ความหมาย | คืนค่า true เมื่อ |
|---|---|---|
| IsSubsetOf | เป็น subset (รวม equal) | สมาชิกทุกตัวอยู่ใน other |
| IsProperSubsetOf | เป็น proper subset | เป็น subset และไม่เท่ากับ other |
| IsSupersetOf | เป็น superset (รวม equal) | มีสมาชิกครบทุกตัวของ other |
| IsProperSupersetOf | เป็น proper superset | เป็น superset และไม่เท่ากับ other |
| SetEquals | เท่ากัน (สมาชิกเหมือนกันทุกตัว) | สองเซตมีสมาชิกเหมือนกันทุกตัว |
| Overlaps | มีสมาชิกร่วมกันอย่างน้อย 1 ตัว | Intersection ≠ ∅ |