How to resolve collection was modified enumeration operation may not execute?

How to resolve collection was modified enumeration operation may not execute?

System. InvalidOperationException: Collection was modified; enumeration operation may not execute

  1. Solution 1 – If you’re removing items, use RemoveAll()
  2. Solution 2 – If you’re adding items, put them in a temp and use AddRange()
  3. Solution 3 – Use a regular for loop and loop in reverse.

Was modified enumeration operation may not execute?

Why the error Collection was modified; enumeration operation may not execute occurs and how to handle it in C#? 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.

Which is enumeration operation may not execute?

C# Collection was modified; enumeration operation may not execute. wherein you modify the collection rankings. In particular, the offensive line is That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

Can a collection be modified during enumeration operation?

It is related to using this: I initally declare the diciontary globally with this: 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.

Why do I get error C # collection was modified?

I am create an project estimation program and am getting the following error: C# Collection was modified; enumeration operation may not execute. It is related to using this: I initally declare the diciontary globally with this: Any collection that you iterate over with foreach may not be modified during iteration.

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.