C# RemoveAll

All extension method

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.

Predicate

Example

First, this example removes all elements with values of 2. The lambda expression, with the => syntax, matches elements with value of 2. You could use another expression, such as item => item != 2, to remove elements not equal to 2.

Lambda Expression
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 expression syntax

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.

Info:Usually, lambda expressions are best kept simple to preserve code clarity. For complex methods, using a full declaration is simpler.

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."

Discussion

Programming tip

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. The best removal method is determined by the context.

Tip:This site has more information on Remove, and much more information on Lists in general.

List Remove Methods

Summary

C# programming language

You can use the RemoveAll method on the List type in the C# language. We noted how to use a lambda expression as the Predicate object to this method, and how you can read lambda expressions.

Thus:Using the RemoveAll method instead of a complex loop with multiple tests and copies can make code more readable.


C#: Collections: List