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

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

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

ตัวอย่างที่ 1: ลบตัวเลขที่หาร 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)
    {
        SortedSet<int> set1 = new SortedSet<int>();
        set1.Add(200);
        set1.Add(215);
        set1.Add(310);
        set1.Add(500);
        set1.Add(600);

        Console.WriteLine("SortedSet elements...");
        foreach (int i in set1)
        {
            Console.WriteLine(i);
        }

        Console.WriteLine();

        set1.RemoveWhere(Demo);

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

ผลลัพธ์

SortedSet elements...
200
215
310
500
600

SortedSet after removing some elements...
215

ตัวอย่างที่ 2: ลบค่าเฉพาะ 500

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool Demo(int i)
    {
        return (i == 500); // เฉพาะค่า 500
    }

    public static void Main(String[] args)
    {
        SortedSet<int> set1 = new SortedSet<int>();
        set1.Add(200);
        set1.Add(215);
        set1.Add(310);
        set1.Add(500);
        set1.Add(600);

        Console.WriteLine("SortedSet elements...");
        foreach (int i in set1)
        {
            Console.WriteLine(i);
        }

        Console.WriteLine();

        set1.RemoveWhere(Demo);

        Console.WriteLine("SortedSet after removing an element...");
        foreach (int i in set1)
        {
            Console.WriteLine(i);
        }
    }
}

ผลลัพธ์

SortedSet elements...
200
215
310
500
600

SortedSet after removing an element...
200
215
310
600

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

  • RemoveWhere(Predicate<T> match) ลบสมาชิกทุกตัวที่ predicate คืน true
  • Predicate คือ delegate: Func<T, bool> หรือ method ที่รับ T คืน bool
  • คืนค่าจำนวนสมาชิกที่ถูกลบ (int)
  • SortedSet จัดเรียงอัตโนมัติ - หลังลบแล้วลำดับยังคงถูกต้อง
  • เวลา complexity: O(m log n) โดย m = จำนวนที่ถูกลบ, n = จำนวนทั้งหมด
  • สามารถใช้ lambda expression: set.RemoveWhere(x => x % 10 == 0);
  • Method คล้ายกันใน List<T>: RemoveAll(Predicate<T>)