Suppose that I have the following code snippet:
var data=new List<string>(){"One","Two","Three"};
for(int i=0 ; i<data.Count ; i++){
if(data[i]=="One"){
data.RemoveAt(i);
}
}
The following code throws exception.
My question is what is the best way to avoid this exception and to remove the element while looping?
If you need to remove elements then you must iterate backwards so you can remove elements from the end of the list:
However, there are more efficient ways to do this with LINQ (as indicated by the other answers).