Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Xóa phần tử khỏi HashSet trong C#

HashSet<T> là tập hợp không trùng lặp, tra cứu O(1). Xóa phần tử dùng Remove hoặc RemoveWhere.

Ví dụ minh họa

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var names = new HashSet { "Tim", "John", "Tom", "Kevin" };
        
        Console.WriteLine("HashSet ban đầu:");
        foreach (var n in names) Console.WriteLine(n);
        
        // Xóa 1 phần tử cụ thể - trả về bool
        bool removed = names.Remove("John");
        Console.WriteLine($"\nXóa 'John': {removed}"); // True
        
        // Xóa phần tử không tồn tại
        removed = names.Remove("Alice");
        Console.WriteLine($"Xóa 'Alice': {removed}"); // False
        
        // Xóa theo điều kiện (RemoveWhere)
        names.RemoveWhere(name => name.StartsWith("T"));
        Console.WriteLine("\nSau khi xóa tên bắt đầu bằng 'T':");
        foreach (var n in names) Console.WriteLine(n);
        
        // Clear tất cả
        // names.Clear();
    }
}

Kết quả đầu ra

HashSet ban đầu:
Tim
John
Tom
Kevin

Xóa 'John': True
Xóa 'Alice': False

Sau khi xóa tên bắt đầu bằng 'T':
Kevin

Phương thức hữu ích khác: Contains (O(1) check tồn tại), UnionWith, IntersectWith, ExceptWith, SymmetricExceptWith, IsSubsetOf, IsSupersetOf.