Remove item from List while iterating – C#

Removing elements from List<> while iterating over the List, someone may simply try:

foreach(char c in list) 

When we execute this code, we will get System.InvalidOperationException with the message

“Collection was modified; enumeration  operation may not execute.”

The reason is:
The first time the loop executes, it deletes the first element from the list, and in the second iteration, the Exception occurs because the first item is deleted and the List has changed.
Because List will reposition its elements as we delete one of them.

We could do the following method to get our result:

We can iterate the List in a backward direction and remove elements according to our criterion.

for(int i=list.Count - 1; i > -1; i--) 

In this way, the List will not reposition the elements we haven’t iterated yet.
Hence we get our desired results.