How to fix collection was modified enumeration operation may not execute?
System. InvalidOperationException: Collection was modified; enumeration operation may not execute
- Solution 1 – If you’re removing items, use RemoveAll()
- Solution 2 – If you’re adding items, put them in a temp and use AddRange()
- Solution 3 – Use a regular for loop and loop in reverse.
What is collection was modified enumeration operation may not execute?
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.
Why was the error collection was modified ; enumeration?
Why the error Collection was modified; enumeration operation may not execute occurs and how to handle it in C#? Csharp Server Side Programming Programming. This error occurs when a looping process is being running on a collection (Ex: List) and the collection is modified (data added or removed) during the runtime.
Can a collection be modified at the same time?
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.
Can you change the value of an item in a collection?
You are allowed to change the value in an item in a collection. The error you’re getting means that an item was either added or removed i.e.: the collection itself was modified, not an item inside the collection. This is most likely caused by another thread adding or removing items to this collection.
Can a collection be modified with foreach during iteration?
Any collection that you iterate over with foreach may not be modified during iteration. So while you’re running a foreach over rankings, you cannot modify its elements, add new ones or delete any. Share Improve this answer