Click here to Skip to main content
11,478,174 members (70,543 online)
Click here to Skip to main content

Tagged as

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

, 4 May 2013 CPOL 12.3K 4
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

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 Pin
OriginalGriff4-May-13 4:48
mvpOriginalGriff4-May-13 4:48 
AnswerRe: My vote of 1 Pin
abhishek_jmk4-May-13 5:44
memberabhishek_jmk4-May-13 5:44 
GeneralRe: My vote of 1 Pin
OriginalGriff4-May-13 5:59
mvpOriginalGriff4-May-13 5:59 
AnswerRe: My vote of 1 Pin
abhishek_jmk4-May-13 6:49
memberabhishek_jmk4-May-13 6:49 
GeneralMy vote of 1 Pin
Member 6384-May-13 4:19
memberMember 6384-May-13 4:19 
AnswerRe: My vote of 1 Pin
abhishek_jmk4-May-13 4:23
memberabhishek_jmk4-May-13 4:23 
GeneralMy vote of 2 Pin
Guillaume Leparmentier4-May-13 1:53
memberGuillaume Leparmentier4-May-13 1:53 
AnswerRe: My vote of 2 Pin
abhishek_jmk4-May-13 2:43
memberabhishek_jmk4-May-13 2:43 
QuestionYou misunderstood your own code Pin
Oleg Shilo3-May-13 21:11
memberOleg Shilo3-May-13 21:11 
AnswerRe: You misunderstood your own code Pin
abhishek_jmk4-May-13 2:37
memberabhishek_jmk4-May-13 2:37 
GeneralRe: You misunderstood your own code Pin
Oleg Shilo4-May-13 2:53
memberOleg Shilo4-May-13 2:53 
BugMethod 1 can fail subtly! Pin
Matt T Heffron3-May-13 13:11
professionalMatt T Heffron3-May-13 13:11 
AnswerRe: Method 1 can fail subtly! Pin
abhishek_jmk3-May-13 19:00
memberabhishek_jmk3-May-13 19:00 
GeneralMy vote of 5 Pin
Jerome Vibert3-May-13 11:16
memberJerome Vibert3-May-13 11:16 
GeneralRe: My vote of 5 Pin
abhishek_jmk3-May-13 19:22
memberabhishek_jmk3-May-13 19:22 
GeneralRe: My vote of 5 Pin
Daniel Abbatt5-May-13 0:02
memberDaniel Abbatt5-May-13 0:02 
AnswerRe: My vote of 5 Pin
abhishek_jmk5-May-13 2:29
memberabhishek_jmk5-May-13 2:29 
GeneralA quicker way Pin
r v3-May-13 11:08
memberr v3-May-13 11:08 
AnswerRe: A quicker way Pin
abhishek_jmk3-May-13 19:06
memberabhishek_jmk3-May-13 19:06 
GeneralRe: A quicker way Pin
abhishek_jmk4-May-13 3:31
memberabhishek_jmk4-May-13 3: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 | Terms of Use | Mobile
Web02 | 2.8.150520.1 | Last Updated 4 May 2013
Article Copyright 2013 by Abhishek Kumar Goswami
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid