Collection was modified; enumeration operation may not execute - why?

前端 未结 7 1774
南方客
南方客 2020-11-30 11:38

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

7条回答
  •  渐次进展
    2020-11-30 12:14

    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
    

提交回复
热议问题