บทความนี้สาธิตวิธีตรวจสอบว่า HashSet<T> และคอลเลกชันที่ระบุมีสมาชิกร่วมกัน (overlap) อย่างน้อยหนึ่งตัวหรือไม่ โดยใช้เมธอด Overlaps() ใน C#
ตัวอย่างที่ 1: HashSet ของจำนวนเต็ม — มีสมาชิกร่วมกัน
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet<int> set1 = new HashSet<int>();
set1.Add(25);
set1.Add(50);
set1.Add(75);
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(100);
set2.Add(150);
set2.Add(200);
set2.Add(250);
Console.WriteLine("Elements in HashSet2");
foreach (int val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("Do they share common elements? " + set1.Overlaps(set2));
}
}
ผลลัพธ์
Elements in HashSet1 25 50 75 100 125 150 Elements in HashSet2 30 60 100 150 200 250 Do they share common elements? True
ตัวอย่างที่ 2: HashSet ของสตริง — มีสมาชิกร่วมกัน
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet<string> set1 = new HashSet<string>();
set1.Add("Nathan");
set1.Add("Tim");
set1.Add("Tom");
set1.Add("Jack");
set1.Add("Steve");
set1.Add("David");
Console.WriteLine("Elements in HashSet1");
foreach (string val in set1)
{
Console.WriteLine(val);
}
HashSet<string> set2 = new HashSet<string>();
set2.Add("Tom");
set2.Add("Jack");
set2.Add("Kevin");
Console.WriteLine("Elements in HashSet2");
foreach (string val in set2)
{
Console.WriteLine(val);
}
Console.WriteLine("Do they share common elements? " + set1.Overlaps(set2));
}
}
ผลลัพธ์
Elements in HashSet1 Nathan Tim Tom Jack Steve David Elements in HashSet2 Tom Jack Kevin Do they share common elements? True
สรุป
- ใช้
Overlaps(IEnumerable<T> other)เพื่อตรวจสอบว่ามีสมาชิกร่วมกันอย่างน้อย 1 ตัวหรือไม่ — คืนค่าbool - คืนค่า
trueหาก intersection ≠ ∅, มิฉะนั้นfalse - พารามิเตอร์รับ
IEnumerable<T>— ใช้กับ array, List, HashSet, SortedSet, หรือคอลเลกชันอื่นๆ ได้ - Complexity: O(n) โดย n = จำนวนสมาชิกใน other (ตรวจสอบแต่ละตัวใน other ว่าอยู่ใน HashSet นี้หรือไม่ — O(1) ต่อตัว)
- HashSet ใช้ hash table —
Contains,Add,Removeเร็ว O(1) เฉลี่ย
ตารางสรุปเมธอดเซต HashSet
| เมธอด | คำอธิบาย | คืนค่า true เมื่อ |
|---|---|---|
| Overlaps(other) | มีสมาชิกร่วมกัน | Intersection ≠ ∅ |
| SetEquals(other) | สมาชิกเหมือนกันทุกตัว | A = B |
| IsSubsetOf(other) | เป็น subset (รวม equal) | A ⊆ B |
| IsProperSubsetOf(other) | เป็น proper subset | A ⊂ B |
| IsSupersetOf(other) | เป็น superset (รวม equal) | A ⊇ B |
| IsProperSupersetOf(other) | เป็น proper superset | A ⊃ B |
| UnionWith(other) | รวม (A ∪ B) | แก้ไขเซตปัจจุบัน |
| IntersectWith(other) | เก็บเฉพาะร่วมกัน (A ∩ B) | แก้ไขเซตปัจจุบัน |
| ExceptWith(other) | ลบที่อยู่ใน other (A \ B) | แก้ไขเซตปัจจุบัน |
| SymmetricExceptWith(other) | เก็บที่ต่างกัน (A Δ B) | แก้ไขเซตปัจจุบัน |