在foreach循环中修改列表 [英] Modifying list inside foreach loop

查看:200
本文介绍了在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 构造,循环的可以让你改变列表。

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