You can convert the
foreach
into a
for
loop, but even then every time you call
RemoveChild
, you must adjust the loop variable if you are using a cached length condition to exit the
for
loop.
Actually, even if you do not cache the
for
-condition, you still need to adjust the loop variable. For an example, see the code snippet below:
var list = new int[] { 1, 2, 3, 4, 8, 6, 7, 5 }.ToList();
for (int i = 0; i < list.Count; i++)
{
if (list[i] % 2 == 0)
list.RemoveAt(i--);
}
foreach (var item in list)
{
Console.WriteLine(item);
}