RemoveAll
This C# method 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. We can read it like a sentence: remove all elements matching this condition.
Here we demonstrate the RemoveAll
method on the C# List
. We use a function argument (a lambda) to specify which elements to remove.
List
of ints. We then call Add()
with 5 separate integers to populate the list.foreach
loop on the list that we modified with RemoveAll
. And we print the elements.using System; using System.Collections.Generic; // Step 1: create List. List<int> list = new List<int>(); list.Add(1); list.Add(2); list.Add(2); list.Add(4); list.Add(5); // Step 2: remove all list items with value of 2. // ... The lambda expression is the Predicate. list.RemoveAll(item => item == 2); // Step 3: display results. foreach (int i in list) { Console.WriteLine(i); }1 4 5
When called, RemoveAll
will invoke the Predicate
method passed to it. After this is done, it will return an int
equal to the number of elements it removed from the List
.
int
is the count of items removed—so if 2 items are removed, the return value is 2.RemoveAll
will return 0. We can check for 0 to see if the list remained unchanged.List
contents by calling the string.Join
method, which supports a List
argument.using System; using System.Collections.Generic; class Program { static bool IsRemovable(string item) { return item.StartsWith("b"); } static bool IsRemovableNothingMatches(string item) { return item == "x"; } static void Main() { var items = new List<string> { "bird", "frog", "bat" }; Console.WriteLine("ITEMS: {0}", string.Join(",", items)); // Remove 2 items, the result value is 2. var result = items.RemoveAll(IsRemovable); Console.WriteLine("COUNT OF ITEM REMOVED: {0}", result); Console.WriteLine("ITEMS: {0}", string.Join(",", items)); // Nothing is removed with this call. var result2 = items.RemoveAll(IsRemovableNothingMatches); // The result is 0. Console.WriteLine("COUNT, NOTHING REMOVED: {0}", result2); } }ITEMS: bird,frog,bat COUNT OF ITEM REMOVED: 2 ITEMS: frog COUNT, NOTHING REMOVED: 0
When reading the lambda expression, it helps to think of it as "goes to." So you can say that the RemoveAll
invocation above "removes all elements where the value goes to 2."
There are other removal methods on List
like the Remove
and RemoveAt
methods. If you want to remove an isolated element, use those methods instead.
You can use the RemoveAll
method on the List
. We noted how to 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 make code more readable. But be careful to keep your lambda expressions as short
as possible.