C# List - Removing items while looping / iterating [duplicate]
If you need to remove elements then you must iterate backwards so you can remove elements from the end of the list:
var data=new List<string>(){"One","Two","Three"};
for(int i=data.Count - 1; i > -1; i--)
{
if(data[i]=="One")
{
data.RemoveAt(i);
}
}
However, there are more efficient ways to do this with LINQ (as indicated by the other answers).
You can use List<T>.RemoveAll
to handle this:
data.RemoveAll(elem => elem == "One");