I\'m enumerating over a collection that implements IList, and during the enumeration I am modifying the collection. I get the error, \"Collection was modified; enumeration
While others have described why it's invalid behaviour, they haven't offered up a solution to your problem. While you may not need a solution, I'm going to provide it anyway.
If you want to observe a collection that is different to the collection that you are iterating over, you must return a new collection.
For instance..
IEnumerable sequence = Enumerable.Range(0, 30);
IEnumerable newSequence = new List();
foreach (var item in sequence) {
if (item < 20) newSequence.Add(item);
}
// now work with newSequence
This is how you should be 'modifying' collections. LINQ takes this approach when you want to modify a sequence. For instance:
var newSequence = sequence.Where(item => item < 20); // returns new sequence