
RemoveAll filters and removes elements. It can be used with a lambda expression. This reduces the size of your code and improves its clarity. The List RemoveAll method accepts a Predicate expression for this purpose.
This C# example program uses the RemoveAll method on the List type.

First, here we see how you can use the RemoveAll method on List. This example removes all elements with values of 2. The lambda expression, with the => syntax, matches elements with value of 2. You could insert another expression, such as item => item != 2, to remove elements not equal to 2.
Program that uses RemoveAll method [C#]
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(2);
list.Add(4);
list.Add(5);
// Remove all list items with value of 2.
// The lambda expression is the Predicate.
list.RemoveAll(item => item == 2);
// Display results.
foreach (int i in list)
{
Console.WriteLine(i);
}
}
}
Output
1
4
5
Lambda expressions. In the C# programming language, a lambda expression is a compact syntax form of an anonymous delegate method. You can use the delegate keyword with an optional parameter list and a method body instead of a lambda expression. Usually, lambda expressions are best kept simple to preserve code clarity; for complex methods, using a full declaration is simpler.
Reading the expression. When reading the lambda expression operator => in the C# language, it helps to think of it as "goes to"; so you can say that the RemoveAll invocation about "removes all elements where the value goes to 2."
Lambda Expression
You can find more information about removing elements from the List instances in your programs. There are several other methods in the Remove family on List, including the Remove and RemoveAt methods. If you want to remove an isolated element, use those methods instead. This site has more information on Remove, and much more information on Lists in general.
List Remove Methods
We saw how you can use the RemoveAll method on the List type in the C# programming language. We noted how you can use a lambda expression as the Predicate object to this method, and how you can read lambda expressions. Using the RemoveAll method instead of a complex loop with multiple tests and copies can really make code more readable.
Collections