Collection was modified; enumeration operation may not execute

后端 未结 16 2550
南旧
南旧 2020-11-21 06:05

I can\'t get to the bottom of this error, because when the debugger is attached, it does not seem to occur.

Collection was modified; enumeration operatio

16条回答
  •  我在风中等你
    2020-11-21 06:48

    Why this error?

    In general .Net collections do not support being enumerated and modified at the same time. If you try to modify the collection list during enumeration, it raises an exception. So the issue behind this error is, we can not modify the list/dictionary while we are looping through the same.

    One of the solutions

    If we iterate a dictionary using a list of its keys, in parallel we can modify the dictionary object, as we are iterating through the key-collection and not the dictionary(and iterating its key collection).

    Example

    //get key collection from dictionary into a list to loop through
    List keys = new List(Dictionary.Keys);
    
    // iterating key collection using a simple for-each loop
    foreach (int key in keys)
    {
      // Now we can perform any modification with values of the dictionary.
      Dictionary[key] = Dictionary[key] - 1;
    }
    

    Here is a blog post about this solution.

    And for a deep dive in StackOverflow: Why this error occurs?

提交回复
热议问题