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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With