ภาพรวม
HashSet<T> เป็นคอลเลกชันที่ไม่มีค่าซ้ำ ใช้ Remove หรือ RemoveWhere เพื่อลบข้อมูล
โค้ดตัวอย่าง
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
var names = new HashSet<string>();
names.Add("Tim");
names.Add("John");
names.Add("Tom");
names.Add("Kevin");
Console.WriteLine("Initial Set:");
foreach (var name in names) Console.WriteLine(name);
// ลบด้วย Remove (คืนค่า bool: ลบสำเร็จหรือไม่)
bool removed = names.Remove("John");
Console.WriteLine($"\nRemoved 'John': {removed}");
// ลบด้วย RemoveWhere (Predicate)
int countRemoved = names.RemoveWhere(name => name.StartsWith("T"));
Console.WriteLine($"Removed names starting with 'T': {countRemoved}");
Console.WriteLine("\nFinal Set:");
foreach (var name in names) Console.WriteLine(name);
}
}
ผลลัพธ์
Initial Set:
Tim
John
Tom
Kevin
Removed 'John': True
Removed names starting with 'T': 2
Final Set:
Kevin
เมธอดหลักสำหรับการลบ
| Method | Return | คำอธิบาย |
|---|---|---|
Remove(T) | bool | ลบ item เฉพาะตัว คืน true ถ้าพบและลบได้ |
RemoveWhere(Predicate<T>) | int | ลบ items ทุกตัวที่ match predicate คืนจำนวนที่ลบ |
Clear() | void | ลบทั้งหมด |
ExceptWith(IEnumerable<T>) | void | ลบ items ที่อยู่ใน collection อื่น (Set difference) |
IntersectWith(IEnumerable<T>) | void | เก็บแค่ items ที่อยู่ในทั้งสอง (Set intersection) |
การใช้งาน ExceptWith (Set Difference)
var set1 = new HashSet<int> { 1, 2, 3, 4, 5 };
var set2 = new HashSet<int> { 3, 4, 5, 6, 7 };
set1.ExceptWith(set2);
// set1 = { 1, 2 }
ประสิทธิภาพ
Remove: O(1) Average caseRemoveWhere: O(n) ต้องตรวจสอบทุก elementHashSetเร็วกว่าListมากสำหรับการค้นหา/ลบ (O(1) vs O(n))
ข้อควรระวัง
- การ modify HashSet ขณะ enumerate (foreach) จะ throw InvalidOperationException
- ใช้
ToList()หรือToArray()ก่อนลบถ้าต้อง iterate พร้อมกัน