Click here to Skip to main content
15,880,725 members
Articles / Programming Languages / C#
Tip/Trick

How to Insert or Delete Elements to Collection During Iteration in foreach Loop

Rate me:
Please Sign up or sign in to vote.
3.00/5 (8 votes)
4 May 2013CPOL1 min read 46.5K   4   20
This helps to resolve the problem of inserting or removing items from collection during iteration.

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.

Using the Code

We have an integer collection:

C#
List<int> lstObj= new List<int>(){ 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:

C#
foreach (int i in listObj)
       {
           if (i == 10)
           {
               listObj.Remove(i);
           }
       }  

This code generates a run time exception when we execute the code:

Image 1

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 two of the easiest ways.

Method 1

We need to iterate this collection as follows:

C#
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:

C#
foreach (int i in listObj.Reverse<int>())
   {
       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.

Points of Interest

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I like to code and I really enjoy to share my knowledge with all, Its my passion.

http://abhishekgoswami.com/

Comments and Discussions

 
GeneralMy vote of 1 Pin
OriginalGriff4-May-13 3:48
mveOriginalGriff4-May-13 3:48 
AnswerRe: My vote of 1 Pin
Abhishek Kumar Goswami4-May-13 4:44
professionalAbhishek Kumar Goswami4-May-13 4:44 
GeneralRe: My vote of 1 Pin
OriginalGriff4-May-13 4:59
mveOriginalGriff4-May-13 4:59 
AnswerRe: My vote of 1 Pin
Abhishek Kumar Goswami4-May-13 5:49
professionalAbhishek Kumar Goswami4-May-13 5:49 
GeneralMy vote of 1 Pin
Member 6384-May-13 3:19
Member 6384-May-13 3:19 
AnswerRe: My vote of 1 Pin
Abhishek Kumar Goswami4-May-13 3:23
professionalAbhishek Kumar Goswami4-May-13 3:23 
GeneralMy vote of 2 Pin
Guillaume Leparmentier4-May-13 0:53
Guillaume Leparmentier4-May-13 0:53 
AnswerRe: My vote of 2 Pin
Abhishek Kumar Goswami4-May-13 1:43
professionalAbhishek Kumar Goswami4-May-13 1:43 
QuestionYou misunderstood your own code Pin
Oleg Shilo3-May-13 20:11
Oleg Shilo3-May-13 20:11 
AnswerRe: You misunderstood your own code Pin
Abhishek Kumar Goswami4-May-13 1:37
professionalAbhishek Kumar Goswami4-May-13 1:37 
GeneralRe: You misunderstood your own code Pin
Oleg Shilo4-May-13 1:53
Oleg Shilo4-May-13 1:53 
BugMethod 1 can fail subtly! Pin
Matt T Heffron3-May-13 12:11
professionalMatt T Heffron3-May-13 12:11 
AnswerRe: Method 1 can fail subtly! Pin
Abhishek Kumar Goswami3-May-13 18:00
professionalAbhishek Kumar Goswami3-May-13 18:00 
GeneralMy vote of 5 Pin
Jerome Vibert3-May-13 10:16
Jerome Vibert3-May-13 10:16 
GeneralRe: My vote of 5 Pin
Abhishek Kumar Goswami3-May-13 18:22
professionalAbhishek Kumar Goswami3-May-13 18:22 
GeneralRe: My vote of 5 Pin
Daniel Abbatt4-May-13 23:02
Daniel Abbatt4-May-13 23:02 
AnswerRe: My vote of 5 Pin
Abhishek Kumar Goswami5-May-13 1:29
professionalAbhishek Kumar Goswami5-May-13 1:29 
GeneralA quicker way Pin
r v3-May-13 10:08
r v3-May-13 10:08 
AnswerRe: A quicker way Pin
Abhishek Kumar Goswami3-May-13 18:06
professionalAbhishek Kumar Goswami3-May-13 18:06 
GeneralRe: A quicker way Pin
Abhishek Kumar Goswami4-May-13 2:31
professionalAbhishek Kumar Goswami4-May-13 2:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.