C#中RemoveAll
方法用于根据指定条件删除List中符合条件的所有元素。以下是一些RemoveAll
方法的技巧:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
numbers.RemoveAll(num => num % 2 == 0);
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
numbers.RemoveAll(delegate(int num) { return num % 2 == 0; });
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
numbers = numbers.Where(num => num % 2 != 0).ToList();
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 }
};
people.RemoveAll(person => person.Age > 25);
public static class ListExtensions
{
public static void RemoveAll<T>(this List<T> list, Func<T, bool> predicate)
{
for (int i = list.Count - 1; i >= 0; i--)
{
if (predicate(list[i]))
{
list.RemoveAt(i);
}
}
}
}
这些技巧可以帮助您更灵活地使用RemoveAll
方法来删除List中符合条件的元素。