修改foreach循环内的列表 [英] Modifying list inside foreach loop

查看:51
本文介绍了修改foreach循环内的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的结构(但很多更复杂):

I have a construction similar to this (but a lot more complicated):

var list = new List<string>();

// .. populate list ..

foreach(var item in list)
{
    DoFunction(list);
}

public void DoFunction(List<string> list)
{
    if(someCondition == true)
    {
        // .. modify list in here ..
    }
}

现在,我知道无法编辑您正在遍历的集合,但是如果您必须编辑列表(没有 try catch 声明)?有什么方法可以判断列表是否已被编辑?你能编辑列表并在它注意到之前快速break;吗?

Now, I understand that its not possible to edit the collection you're foreaching through, but how do you jump out of the loop gracefully if you do have to edit the list (without a try catch statement)? Is there some way to tell if the list has been edited? Can you edit the list and quickly break; before it notices?

推荐答案

不是使用 foreach 构造,for 循环将允许您更改列表.

Rather than use a foreach construct, a for loop would allow you to alter the list.

for (var x = 0; x < list.Count; x++) {

}

这篇关于修改foreach循环内的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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