Why am I getting "Collection was modified; enumeration operation may not execute" when not modifying
- by ccornet
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?