Introduction
When we add or remove elements from a collection during iteration in foreach loop, then we get an exception. So in this tip, I am going to explain the reason and solutions to resolve this problem. Here, we are going to use some other ways to iterate collection.
How to solve
We have an integer collection:
List lstObj= new List(){ 1, 3, 4, 5, 7, 8, 9, 10, 15 };
Suppose we need to remove element which has a value 10, while iterating through this collection, so we have the following code for this:
foreach (int i in listObj)
{
if (i == 10)
{
listObj.Remove(i);
}
}
This code generates a run time exception when we execute the code:

Now let me explain the reason behind it. Since by default, collection is not
thread safe so multiple readers can read the collection with confidence.
However, any modification to the collection generates undefined results for all
threads that access the collection, including the reader thread.
There can be many ways to resolve this issue, but here, I am explaining three of
the easiest ways.

Join the conversation! Your thoughts help the community grow.