Dealing with Collection was modified – enumeration operation may not execute


Dealing with Collection was modified – enumeration operation may not execute

Collection

So, today I ran into a common problem that probably every .NET developer had the pleasure to experience: the infamous Collection was modified; enumeration operation may not execute. Basically, this happens because you can’t modify a collection you’re iterating through.

After a quick search, I found here what I suppose to be the easiest way to get around this issue: simply call the ToArray/ToList/ToWhatever LINQ method. For example, the code below won’t work:

List<string> goodProgrammingLanguages = GetGoodProgrammingLanguages();
foreach(var language in goodProgrammingLanguages)
{
    if(language == "Java")
        goodProgrammingLanguages.Remove(language);
}

But this one will work just fine:

List<string> goodProgrammingLanguages = GetGoodProgrammingLanguages();
foreach(var language in goodProgrammingLanguages.ToArray())
{
    if(language == "Java")
        goodProgrammingLanguages.Remove(language);
}

And that’s it! Hope this can help you avoid lenghty workarounds.