เมธอด HashSet<T>.IsSubsetOf() ใน C# ใช้สำหรับตรวจสอบว่า HashSet ปัจจุบันเป็นเซตย่อย (subset) ของคอลเลกชันที่ระบุหรือไม่ — หมายถึงทุกองค์ประกอบใน HashSet นี้ ต้องมีอยู่ในคอลเลกชันเป้าหมาย
ตัวอย่างที่ 1: ไม่ใช่เซตย่อย
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet set1 = new HashSet();
set1.Add("EF");
set1.Add("OP");
Console.WriteLine("Elements in HashSet1:");
foreach (string val in set1)
{
Console.WriteLine(val);
}
HashSet set2 = new HashSet();
set2.Add("KL");
set2.Add("MN");
set2.Add("OP");
set2.Add("QR");
Console.WriteLine("\nElements in HashSet2:");
foreach (string val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("\nIs set1 a subset of set2? " + set1.IsSubsetOf(set2));
}
}
ผลลัพธ์
Elements in HashSet1: EF OP Elements in HashSet2: KL MN OP QR Is set1 a subset of set2? False
ตัวอย่างที่ 2: เป็นเซตย่อย
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet set1 = new HashSet();
set1.Add("EF");
set1.Add("OP");
Console.WriteLine("Elements in HashSet1:");
foreach (string val in set1)
{
Console.WriteLine(val);
}
HashSet set2 = new HashSet();
set2.Add("EF");
set2.Add("OP");
set2.Add("QR");
Console.WriteLine("\nElements in HashSet2:");
foreach (string val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("\nIs set1 a subset of set2? " + set1.IsSubsetOf(set2));
}
}
ผลลัพธ์
Elements in HashSet1: EF OP Elements in HashSet2: EF OP QR Is set1 a subset of set2? True
เมธอดเซตที่เกี่ยวข้อง (Set Operations)
| เมธอด | คำอธิบาย |
|---|---|
IsSubsetOf(other) | เซตนี้ ⊆ other (ทุกตัวอยู่ใน other) |
IsProperSubsetOf(other) | เซตนี้ ⊂ other (เป็น subset และไม่เท่ากัน) |
IsSupersetOf(other) | เซตนี้ ⊇ other (ครอบคลุม other) |
IsProperSupersetOf(other) | เซตนี้ ⊃ other (เป็น superset และไม่เท่ากัน) |
Overlaps(other) | มีองค์ประกอบร่วมกันอย่างน้อย 1 ตัว |
SetEquals(other) | มีองค์ประกอบเหมือนกันทุกตัว (เท่ากัน) |
ข้อสังเกตสำคัญ
IsSubsetOfรับIEnumerable<T>— สามารถส่ง List, Array, HashSet อื่นได้- การทำงานเป็น O(n) โดย n = จำนวนองค์ประกอบในเซตนี้ (ใช้ Hash lookup)
- เซตว่าง (empty set) เป็น subset ของทุกเซต — คืน
trueเสมอ - HashSet ไม่เก็บค่าซ้ำ และไม่มีลำดับ
- เหมาะสำหรับการตรวจสอบสิทธิ์, ตัวกรอง, การคำนวณเซตทางคณิตศาสตร์