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

Xóa phần tử từ HashSet theo điều kiện predicate trong C#

Giới thiệu

Để xóa các phần tử khỏi HashSet<T> dựa trên một điều kiện (predicate), bạn sử dụng phương thức RemoveWhere(Predicate<T> match). Phương thức xóa tất cả phần tử thỏa mãn điều kiện và trả về số lượng phần tử đã xóa. Thứ tự duyệt trong HashSet không được đảm bảo.

Ví dụ 1: Xóa phần tử bằng 100

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool Demo(int i)
    {
        return (i == 100);
    }

    public static void Main(String[] args)
    {
        HashSet<int> list = new HashSet<int>();
        list.Add(100);
        list.Add(300);
        list.Add(400);
        list.Add(500);
        list.Add(600);

        Console.WriteLine("Các phần tử của HashSet...");
        foreach (int i in list)
            Console.WriteLine(i);

        Console.WriteLine();

        int removed = list.RemoveWhere(Demo);

        Console.WriteLine("HashSet sau khi xóa phần tử 100...");
        foreach (int i in list)
            Console.WriteLine(i);
    }
}

Kết quả

Các phần tử của HashSet...
100
300
400
500
600
HashSet sau khi xóa phần tử 100...
300
400
500
600

Ví dụ 2: Xóa các số chia hết cho 10

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool Demo(int i)
    {
        return (i % 10) == 0;
    }

    public static void Main(String[] args)
    {
        HashSet<int> list = new HashSet<int>();
        list.Add(100);
        list.Add(355);
        list.Add(400);
        list.Add(555);
        list.Add(600);

        Console.WriteLine("Các phần tử của HashSet...");
        foreach (int i in list)
            Console.WriteLine(i);

        Console.WriteLine();

        list.RemoveWhere(Demo);

        Console.WriteLine("HashSet sau khi xóa một số phần tử...");
        foreach (int i in list)
            Console.WriteLine(i);
    }
}

Kết quả

Các phần tử của HashSet...
100
355
400
555
600
HashSet sau khi xóa một số phần tử...
355
555

Lưu ý: HashSet<T> không giữ thứ tự. RemoveWhere hiệu quả O(n) với n là số phần tử. Predicate là delegate Func<T, bool> hoặc phương thức static trả về bool. Có thể dùng lambda: set.RemoveWhere(x => x % 10 == 0).