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

วิธีลบสมาชิกใน HashSet ตามเงื่อนไข Predicate ใน C#

บทความนี้สาธิตวิธีการลบสมาชิก (elements) ใน HashSet<T> ที่ตรงกับเงื่อนไขที่กำหนดโดย Predicate<T> โดยใช้ method RemoveWhere(Predicate<T> match)

ตัวอย่างที่ 1: ลบค่า 100

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool Demo(int i)
    {
        return (i == 100); // เฉพาะค่า 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("HashSet elements...");
        foreach (int i in list)
        {
            Console.WriteLine(i);
        }

        Console.WriteLine();

        list.RemoveWhere(Demo);

        Console.WriteLine("HashSet after removing element 100...");
        foreach (int i in list)
        {
            Console.WriteLine(i);
        }
    }
}

ผลลัพธ์

HashSet elements...
100
300
400
500
600

HashSet after removing element 100...
300
400
500
600

ตัวอย่างที่ 2: ลบตัวเลขที่หาร 10 ลงตัว

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool Demo(int i)
    {
        return ((i % 10) == 0); // หาร 10 ลงตัว
    }

    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("HashSet elements...");
        foreach (int i in list)
        {
            Console.WriteLine(i);
        }

        Console.WriteLine();

        list.RemoveWhere(Demo);

        Console.WriteLine("HashSet after removing some elements...");
        foreach (int i in list)
        {
            Console.WriteLine(i);
        }
    }
}

ผลลัพธ์

HashSet elements...
100
355
400
555
600

HashSet after removing some elements...
355
555

คำอธิบายเพิ่มเติม

  • RemoveWhere(Predicate<T> match) ลบสมาชิกทุกตัวที่ predicate คืน true
  • คืนค่าจำนวนสมาชิกที่ถูกลบ (int)
  • HashSet ไม่จัดเรียง - ลำดับการวนลูปไม่คาดการณ์ได้
  • เวลา complexity: O(n) - ต้องตรวจสอบทุกสมาชิก (แต่ละการลบ O(1) average)
  • สามารถใช้ lambda expression: set.RemoveWhere(x => x % 10 == 0);
  • Method นี้มีใน .NET Framework 4.5+ และ .NET Core/.NET 5+
  • เหมาะสำหรับการ filter/lazy deletion แทนการลูปลบเอง (ซึ่งจะ error: collection modified)