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

查看:45
本文介绍了C# 列表 - 在循环/迭代时删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码片段:

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

以下代码抛出异常.

我的问题是避免此异常并在循环时删除元素的最佳方法是什么?

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天全站免登陆