This post will discuss how to remove elements from a list in C# that satisfies the given condition while iterating over it.

Problem: We can’t iterate over a list and simply remove elements from it.

Reason: Moving forward in the list using a for-loop and removing elements from it might cause you to skip a few elements. In other words, when the i’th element of the list is removed, the element positioned at the next index becomes the new i’th element. Now in the next iteration of the for-loop, since index i gets incremented, the unprocessed i’th element will be skipped.

This is evident from the following example where the expected output should be empty, but the actual output is [2,4,6,8,10].

Download  Run Code

 
Also, InvalidOperationException will be thrown if we try to move forward in the list using the foreach loop and remove elements from it. This exception is thrown when a method call is invalid for the object’s current state.

Download Code

 
There are several workarounds to solve the above problems:

1. Iterate Backwards

An elegant solution is to iterate backward in the list, which does not skip anything, and we can call the RemoveAt() method for removing elements.

Download  Run Code

2. Using List<T>.Reverse() method

Another solution to get around the above problem is to iterate over a reversed copy of the list using the foreach loop. The following code example shows how to implement this using LINQ’s Reverse() method:

Download Code

3. Decremeting index

We can also decrement index i in the loop when the i'th element is removed from the list. Now, the i'th element will not be skipped.

Download  Run Code

4. Use Another Collection

Instead of removing elements as moving forward in the list, we create a collection of such elements and delete them later. Depending upon the deletion condition used, this approach might fail if the list contains duplicate elements.

Download  Run Code

That’s all about removing elements from a list while iterating over it in C#.