This post will discuss how to remove all occurrences of an item from a List in C#.

1. Using RemoveAll() Method

The List<T>.RemoveAll() method is often used to remove all the elements matching the specified predicate. The predicate should define the conditions of the elements to remove. The following example demonstrates this by removing all occurrences of element 2 from the list:

Download  Run Code

 
Since the RemoveAll() method accepts a predicate, it can be used to conditionally remove elements. For example, the following code creates a list of objects, and then removes all objects with the founded field having a value more than 1920.

Download  Run Code

Output:

[Ford, 1903], [Chevrolet, 1908]

2. Using Remove() Method

The List.Remove() method removes the first occurrence of a specific object from the List and returns true on successful removal. Although highly inefficient, you can make use of the return value of the Remove() method to repeatedly remove an item from the list until all its occurrences are removed, as shown below:

Download  Run Code

3. Using Where() Method

If you need a new list with the desired elements removed without touching the original list, you can use LINQ. The Where() method filters a sequence of values based on a predicate. For example, the following code returns all items except the one having a value of 2.

Download  Run Code

That’s all about removing all occurrences of an item from a List in C#.