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中符合條件的元素。