How add or remove object while iterating Collection in C#

后端 未结 5 1556
佛祖请我去吃肉
佛祖请我去吃肉 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:29

    As the other answers say, a foreach is designed purely for iterating over a collection without modifying it as per the documenation:

    The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.

    in order to do this you would need to use a for loop (storing the items of the collection you need to remove) and remove them from the collection afterwards.

    However if you are using a List you could do this:

    lines.RemoveAll(line => line.FullfilsCertainConditions());
    

提交回复
热议问题