使用 list 方法配合 hashset 可以高效删除不在指定集合中的元素。具体做法是创建一个包含保留元素的 hashset,然后调用 removeall 并传入一个委托,该委托检查当前元素是否不在 hashset 中,这样就能原地过滤出目标子集。

如何验证 RemoveAll 的过滤逻辑与性能表现
RemoveAll 接受一个 Predicate 委托,当委托返回 true 时删除对应元素。为了高效判断元素是否在保留集合中,应使用 HashSet 而非 List,因为 HashSet 的查找时间复杂度为 O(1),而 List 为 O(n)。在下面的示例中,我们定义了一个整数列表和一个保留集合,通过 !set.Contains(item) 来筛选掉非保留元素。

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// 原始数据
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 指定要保留的元素集合
HashSet<int> keepSet = new HashSet<int> { 2, 4, 6, 8, 10 };
Console.WriteLine($"Before: [{string.Join(", ", numbers)}]");
// 删除不在 keepSet 中的元素
int removedCount = numbers.RemoveAll(item => !keepSet.Contains(item));
Console.WriteLine($"Removed: {removedCount}");
Console.WriteLine($"After: [{string.Join(", ", numbers)}]");
}
}</int></int></int></int>
运行上述代码,预期输出如下: Before: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Removed: 5 After: [2, 4, 6, 8, 10]
如果保留集合为空会发生什么
当 HashSet 为空时,Contains 始终返回 false,因此 !keepSet.Contains(item) 始终为 true。这意味着 RemoveAll 会删除列表中的所有元素,最终得到一个空列表。这是符合逻辑的行为,因为没有任何元素被指定为“保留”。

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3 };
HashSet<int> emptySet = new HashSet<int>();
// 模拟空保留集合的情况
int removedCount = numbers.RemoveAll(item => !emptySet.Contains(item));
Console.WriteLine($"Remaining count: {numbers.Count}");
Console.WriteLine($"Removed count: {removedCount}");
}
}</int></int></int></int>
运行结果将显示 Remaining count: 0 和 Removed count: 3,证实了所有元素均被移除。










