Why am I getting "Collection was modified; enumeration operation may not execute" when not modifying

Posted by ccornet on Stack Overflow See other posts from Stack Overflow or by ccornet
Published on 2010-05-07T20:31:51Z Indexed on 2010/05/07 20:38 UTC
Read the original article Hit count: 263

Filed under:
|
|

I have two collections of strings: CollectionA is a StringCollection property of an object stored in the system, while CollectionB is a List generated at runtime. CollectionA needs to be updated to match CollectionB if there are any differences. So I devised what I expected to be a simple LINQ method to perform the removal.

var strDifferences = CollectionA.Where(foo => !CollectionB.Contains(foo));
foreach (var strVar in strDifferences) { CollectionA.Remove(strVar); }

But I am getting a "Collection was modified; enumeration operation may not execute" error on strDifferences... even though it is a separate enumerable from the collection being modified! I originally devised this explicitly to evade this error, as my first implementation would produce it (as I was enumerating across CollectionA and just removing when !CollectionB.Contains(str)). Can anyone shed some insight into why this enumeration is failing?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ