I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from the list.
You can't use .Remove(element)
inside a foreach (var element in X)
(because it results in Collection was modified; enumeration operation may not execute.
exception)… you also can't use for (int i = 0; i < elements.Count(); i++)
and .RemoveAt(i)
because it disrupts your current position in the collection relative to i
.
Is there an elegant way to do this?
Best Answer
Iterate your list in reverse with a for loop:
Example:
Alternately, you can use the RemoveAll method with a predicate to test against:
Here's a simplified example to demonstrate: