温馨提示×

c# removeall能否用于所有集合

c#
小樊
87
2024-07-12 04:53:27
栏目: 编程语言

RemoveAll方法可以用于实现了ICollection接口的集合,包括List、Dictionary、Queue、Stack等。但是对于只实现了IEnumerable接口的集合,如Array、HashSet等,是无法直接调用RemoveAll方法的。

对于只实现了IEnumerable接口的集合,可以先将其转换为List或者其他实现了ICollection接口的集合,然后再调用RemoveAll方法进行元素的移除操作。例如:

HashSet<int> hashSet = new HashSet<int> { 1, 2, 3, 4, 5 };

List<int> list = hashSet.ToList();
list.RemoveAll(x => x % 2 == 0);

foreach (int num in list)
{
    Console.WriteLine(num);
}

在这个例子中,我们首先将HashSet转换为List,然后使用RemoveAll方法移除了所有偶数元素,最后输出了剩余的元素。

0