温馨提示×

c# removeall用法有哪些技巧

c#
小樊
123
2024-07-12 04:49:28
栏目: 编程语言

C#中RemoveAll方法用于根据指定条件删除List中符合条件的所有元素。以下是一些RemoveAll方法的技巧:

  1. 使用Lambda表达式作为条件:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
numbers.RemoveAll(num => num % 2 == 0);
  1. 使用匿名方法作为条件:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
numbers.RemoveAll(delegate(int num) { return num % 2 == 0; });
  1. 结合LINQ查询语句:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
numbers = numbers.Where(num => num % 2 != 0).ToList();
  1. 在条件中使用集合的其他属性:
List<Person> people = new List<Person>
{
    new Person { Name = "Alice", Age = 25 },
    new Person { Name = "Bob", Age = 30 }
};
people.RemoveAll(person => person.Age > 25);
  1. 使用扩展方法:
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中符合条件的元素。

0