Click here to Skip to main content
Click here to Skip to main content
 

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

By , 4 May 2013
Rate this:
Please Sign up or sign in to vote.

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:

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:

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 two 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<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)

About the Author

Abhishek Kumar Goswami
Software Developer
India India
I like to code and I really enjoy to share my knowledge with all, Its my passion.
 
http://allaboutdotnet.com/

Comments and Discussions

 
GeneralMy vote of 1 PinmvpOriginalGriff4-May-13 3:48 
AnswerRe: My vote of 1 Pinmemberabhishek_jmk4-May-13 4:44 
GeneralRe: My vote of 1 PinmvpOriginalGriff4-May-13 4:59 
AnswerRe: My vote of 1 Pinmemberabhishek_jmk4-May-13 5:49 
GeneralMy vote of 1 PinmemberMember 6384-May-13 3:19 
AnswerRe: My vote of 1 Pinmemberabhishek_jmk4-May-13 3:23 
GeneralMy vote of 2 PinmemberGuillaume Leparmentier4-May-13 0:53 
AnswerRe: My vote of 2 Pinmemberabhishek_jmk4-May-13 1:43 
QuestionYou misunderstood your own code PinmemberOleg Shilo3-May-13 20:11 
Your method 2 works not because you reversed it but because Reverse returns another collection. And this, in turn, allows you to modify the original list.
 
You could achieve the same with
listObj.ToList()
listObj.ToArray()
or 
new List<int>(listObj)
 
In fact ToList() is preferred as it does not do unnecessary reversing.
 
foreach (int i in listObj.ToList())
    {
        if (i == 10)
        {
            listObj.Remove(i);
        }
    }

AnswerRe: You misunderstood your own code Pinmemberabhishek_jmk4-May-13 1:37 
GeneralRe: You misunderstood your own code PinmemberOleg Shilo4-May-13 1:53 
BugMethod 1 can fail subtly! PinprofessionalMatt T Heffron3-May-13 12:11 
AnswerRe: Method 1 can fail subtly! Pinmemberabhishek_jmk3-May-13 18:00 
GeneralMy vote of 5 PinmemberJerome Vibert3-May-13 10:16 
GeneralRe: My vote of 5 Pinmemberabhishek_jmk3-May-13 18:22 
GeneralRe: My vote of 5 PinmemberDaniel Abbatt4-May-13 23:02 
AnswerRe: My vote of 5 Pinmemberabhishek_jmk5-May-13 1:29 
GeneralA quicker way Pinmemberr v3-May-13 10:08 
AnswerRe: A quicker way Pinmemberabhishek_jmk3-May-13 18:06 
GeneralRe: A quicker way Pinmemberabhishek_jmk4-May-13 2:31 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 4 May 2013
Article Copyright 2013 by Abhishek Kumar Goswami
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid