Giới thiệu
Để xóa các phần tử khỏi SortedSet<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.
Ví dụ 1: 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)
{
SortedSet<int> set1 = new SortedSet<int>();
set1.Add(200);
set1.Add(215);
set1.Add(310);
set1.Add(500);
set1.Add(600);
Console.WriteLine("Các phần tử của SortedSet...");
foreach (int i in set1)
Console.WriteLine(i);
Console.WriteLine();
int removed = set1.RemoveWhere(Demo);
Console.WriteLine("SortedSet sau khi xóa một số phần tử...");
foreach (int i in set1)
Console.WriteLine(i);
}
}
Kết quả
Các phần tử của SortedSet... 200 215 310 500 600 SortedSet sau khi xóa một số phần tử... 215
Ví dụ 2: Xóa phần tử bằng 500
using System;
using System.Collections.Generic;
public class Demo
{
private static bool Demo(int i)
{
return (i == 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("Các phần tử của SortedSet...");
foreach (int i in set1)
Console.WriteLine(i);
Console.WriteLine();
set1.RemoveWhere(Demo);
Console.WriteLine("SortedSet sau khi xóa một phần tử...");
foreach (int i in set1)
Console.WriteLine(i);
}
}
Kết quả
Các phần tử của SortedSet... 200 215 310 500 600 SortedSet sau khi xóa một phần tử... 200 215 310 600
Lưu ý: RemoveWhere duyệt qua tất cả phần tử, xóa những phần tử làm predicate trả về true. Vì SortedSet đã sắp xếp, thứ tự duyệt là tăng dần. Phương thức trả về int là số phần tử đã xóa (ví dụ 1 không hiển thị giá trị trả về).