This post will discuss how to conditionally remove items from a list in C#.

1. Using List<T>.RemoveAll() Method

To remove elements from a list that satisfies a given predicate in C#, you can use the List<T>.RemoveAll() method. The following code example shows a typical invocation for this method. Note that this uses LINQ.

Download  Run Code

Output:

[Ford, 1903], [Chevrolet, 1908]

2. Using Remove() Method

In order to remove a single occurrence of an element from a list that satisfies a given predicate in C#, you can use the List<T>.Remove() method from LINQ. This method is demonstrated below using the Single() method that returns the only element of a sequence that satisfies a specified condition.

Download  Run Code

Output:

[Ford, 1903], [Chevrolet, 1908], [Toyota, 1937]

 
The List<T>.Remove() method throws System.InvalidOperationException if the sequence contains no matching element. This can be handled using the SingleOrDefault() method that returns a default value if the matching element is not found.

Download  Run Code

Output:

[Ford, 1903], [Chevrolet, 1908], [Toyota, 1937]

 
Note that both Single() and SingleOrDefault() method throws System.InvalidOperationException if the sequence contains more than one matching element. Finally, in order to remove all occurrences of matching elements from a list, you can invoke the List<T>.Remove() method for each matching element. Here’s an example of its usage:

Download  Run Code

Output:

[Ford, 1903], [Toyota, 1937]

That’s all about conditionally removing items from a list in C#.