Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ลบ Item ออกจาก HashSet ใน C#

ภาพรวม

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

เมธอดหลักสำหรับการลบ

MethodReturnคำอธิบาย
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 case
  • RemoveWhere: O(n) ต้องตรวจสอบทุก element
  • HashSet เร็วกว่า List มากสำหรับการค้นหา/ลบ (O(1) vs O(n))

ข้อควรระวัง

  • การ modify HashSet ขณะ enumerate (foreach) จะ throw InvalidOperationException
  • ใช้ ToList() หรือ ToArray() ก่อนลบถ้าต้อง iterate พร้อมกัน