Best practice to avoid InvalidOperationException: Collection was modified?
- by Roflcoptr
Very often I need something like that:
foreach (Line line in lines)
{
if (line.FullfilsCertainConditions())
{
lines.Remove(line)
}
}
This does not work, because I always get a InvalidOperationException because the Enumerator was changed during the loop.
So I changed all my loops of this kind to the following:
List<Line> remove = new List<Line>();
foreach (Line line in lines)
{
if (line.FullfilsCertainConditions())
{
remove.Add(line)
}
}
foreach (Line line in remove) {
{
lines.Remove(line);
}
I'm not sure if this is really the best way since in the worst case I have to iterate 2 times over the original list and so it needs time 2n instead of n.
Is there a better way to do this?