C# 中使用谓词定义的条件从 HashSet 中删除元素
csharpserver side programmingprogramming更新于 2025/8/31 17:37:17
要使用谓词定义的条件从 HashSet 中删除元素,代码如下−
示例
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("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
示例
让我们看另一个例子 −
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("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

