Best practice to avoid InvalidOperationException: Collection was modified?
Posted
by
Roflcoptr
on Stack Overflow
See other posts from Stack Overflow
or by Roflcoptr
Published on 2011-01-17T22:47:01Z
Indexed on
2011/01/17
22:53 UTC
Read the original article
Hit count: 191
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?
© Stack Overflow or respective owner