C#列表 - 删除项目,而循环/迭代

问题描述:

假设我有以下的code片断:

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);
  }
}

下面code抛出异常。

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);
    }
}

但是,也有更有效的方法来使用LINQ(由其他的答案所指示的)。

However, there are more efficient ways to do this with LINQ (as indicated by the other answers).