Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# RemoveAll List Method

This C# example program uses the RemoveAll method on the List type.

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.


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.

C# program that uses RemoveAll method

using System;
using System.Collections.Generic;

class Program
    static void Main()
	List<int> list = new List<int>();

	// 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)



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 above "removes all elements where the value goes to 2."

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

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