You can also use a forward moving loop like:
var data = new List<string>() { "One", "Two", "Three", "One", "One", "Four" };
for (int i = 0; i < data.Count; i++)
{
if (data[i] == "One")
{
data.RemoveAt(i--);
}
}
This line data.RemoveAt(i--);
is stopping the effect of increment in the iteration variable at the end of the loop, in case of item being removed from the list.
It will remove the item from index at the current iteration value and then after removing the item, the iterator would be set to one less value than the current one. At the end of loop, the increment in loop body will move it to next valid index.
Here is a working dotfiddle
(Please note, that I personally use reverse loop for situation like these because IMO, they are easier to understand, this answer here is just for displaying another way of achieving it).
Length
property on a list. – DomenigaLenght
instead ofCount
, your code seems to work fine. (In fact, it does have a bug, but it really shouldn't throw an exception.) – Tuddor