บทความนี้สาธิตวิธีตรวจสอบว่า HashSet<T> มีสมาชิก (element) ที่ระบุอยู่หรือไม่ โดยใช้เมธอด Contains() ใน 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));
Console.WriteLine("Does HashSet1 has element 60? " + set1.Contains(60));
Console.WriteLine("Does HashSet2 has element 60? " + set2.Contains(60));
}
}
ผลลัพธ์
Elements in HashSet1 25 50 75 100 125 150 Elements in HashSet2 30 60 100 150 200 250 Do they share common elements? True Does HashSet1 has element 60? False Does HashSet2 has element 60? True
ตัวอย่างที่ 2: ตรวจสอบสมาชิกใน HashSet ของสตริง พร้อมเงื่อนไข if-else
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
HashSet<string> hashSet = new HashSet<string>();
hashSet.Add("Tim");
hashSet.Add("Jack");
hashSet.Add("Matt");
hashSet.Add("Steve");
hashSet.Add("David");
hashSet.Add("Kane");
hashSet.Add("Gary");
Console.WriteLine("Elements in HashSet");
foreach (string val in hashSet)
{
Console.WriteLine(val);
}
if (hashSet.Contains("Matt"))
Console.WriteLine("The element Matt is in the HashSet");
else
Console.WriteLine("The element Matt is not in the HashSet");
}
}
ผลลัพธ์
Elements in HashSet Tim Jack Matt Steve David Kane Gary The element Matt is in the HashSet
สรุป
- ใช้
Contains(T item)เพื่อตรวจสอบว่ามีสมาชิกอยู่ใน HashSet หรือไม่ — คืนค่าbool - HashSet ใช้ hash table ด้านใน —
Contains()มี complexity O(1) เฉลี่ย (เร็วมาก) - HashSet ไม่จัดเก็บค่าซ้ำ และ ไม่รับประกันลำดับ
- เมธอด
Overlaps(IEnumerable<T> other)ตรวจสอบว่ามีสมาชิกร่วมกันอย่างน้อย 1 ตัวหรือไม่ - เหมาะสำหรับ: ตรวจสอบความซ้ำ, การดำเนินการเซต (union, intersection, difference), lookup ความเร็วสูง
ตารางสรุปเมธอด HashSet ที่เกี่ยวข้อง
| เมธอด | คำอธิบาย | Complexity |
|---|---|---|
| Contains(T) | ตรวจสอบสมาชิก | O(1) เฉลี่ย |
| Add(T) | เพิ่มสมาชิก (ไม่ซ้ำ) | O(1) เฉลี่ย |
| Remove(T) | ลบสมาชิก | O(1) เฉลี่ย |
| Overlaps(IEnumerable<T>) | มีสมาชิกร่วมกันหรือไม่ | O(n) ของ other |
| SetEquals(IEnumerable<T>) | สมาชิกเหมือนกันทุกตัว | O(n) |
| IsSubsetOf / IsProperSubsetOf | เป็น subset / proper subset | O(n) |
| IsSupersetOf / IsProperSupersetOf | เป็น superset / proper superset | O(n) |
| UnionWith / IntersectWith / ExceptWith / SymmetricExceptWith | ดำเนินการเซต | O(n) |