How add or remove object while iterating Collection in C#

后端 未结 5 1558
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 16:52

I am trying to remove object while I am iterating through Collection. But I am getting exception. How can I achieve this? Here is my code :

foreach (var gem          


        
5条回答
  •  无人及你
    2020-12-06 17:36

    Collections support foreach statement using Enumarator. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException. Use for loop for collection modifying.

提交回复
热议问题