Collection was modified; enumeration operation may not execute

Attempting to remove any element from a collection within a foreach loop will result in the above mentioned error.
To stop the error simply add a .ToList() or .ToArray() within the foreach loop as seen below.


List distinctList = new List();
foreach (string item in distinctList.ToList())
{
distinctList.Remove(item);
}

By calling .ToList(), it copies the value of the collection to a separate collection and nothing else has access to it. It does not even have a variable name. As such nothing can modify it in the loop.

Advertisements
This entry was posted in C# and tagged , , , . Bookmark the permalink.

One Response to Collection was modified; enumeration operation may not execute

  1. Anonymous says:

    thanks

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s