Remove items while iterating a collection in C#

C#.NETLINQ

Please contribute by voting. Thanks!
10
So if you iterate a collection (e.g. List) in C# / .NET and try to remove items inside the loop you will get the following error: Collection was modified; enumeration operation may not execute.
foreach(var item in list)
{
if(some_condition)
{
list.Remove(item); //Not possible - will generate error! }
}

What you need to do is to make a copy of the reference to the collection before iterating it, this can be accomplished by calling the .ToList()-method on the collection:
foreach(var item in list.ToList())
{
if(some_condition)
{
list.Remove(item); //Will work! }
}

Article created: Aug 4 '15. Edited Sep 22 '15.

2 Comments

3
Sebastian Lundin [3]  •  Oct 16 '15  •   •  Reply

Nice simple article.

I would like to add the Lambda equivalent for:

foreach(var item in list.ToList())
{
    if(some_condition)
    {
        list.Remove(item);    //Will work!
    }
}

which would be:

list.RemoveAll(listitem => some_condition);
2
Lobo [1]  •  Sep 18 '15  •   •  Reply

Nice one, I created an account here to upvote this one.

Your comment

You need to sign up / log in to comment this article

Author

Created by Robert Bengtsson [126] Aug 4 '15

Share article

Do you know about

Domain-driven Design (DDD)?

Write an article