Insert or Delete Elements to Collection During Iteration in foreach Loop

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:


Image1.jpg


 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.

Method 1

We need to iterate this collection as follows:

for (int i = listObj.Count-1; i >0; i--)
{

    if (listObj[i] == 10)

    {

          listObj.RemoveAt(i);

    }

}
 
Method 2

 We need to iterate the list in reverse order:

 foreach (int i in listObj.Reverse())

 {

     if (i == 10)

     {

         listObj.Remove(i);

     }

 }

Method 3 

We can use LINQ's Where clause to filter the data : 

 listObj = listObj.Where(l => l != 10).ToList();

In all the above methods, since the same thread is not using for modification, that's why it is possible to remove elements from collection while iterating it. We can use the same for adding the elements in collection.

Summary

I faced this problem when I was working in a project where I needed to use a dictionary collection and while iterating this dictionary, I tried to remove elements from this dictionary and then I came to know this problem. It's a very common problem, so I am sharing this.