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
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());