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; });结合LINQ查询语句: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中符合条件的元素。