C#列表 - 删除项目,而循环/迭代 [英] C# List - Removing items while looping / iterating

查看:113
本文介绍了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).

这篇关于C#列表 - 删除项目,而循环/迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆