修改foreach循环内的列表

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

var list = new List(); // .. populate list .. foreach(var item in list) { DoFunction(list); } public void DoFunction(List list) { if(someCondition == true) { // .. modify list in here .. } } 

现在,我明白不可能编辑你正在进行的集合,但如果你必须编辑列表(没有try catch语句),你如何优雅地跳出循环? 有没有办法判断列表是否已被编辑? 你可以编辑列表并快速break; 在它通知之前?

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

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

是的,你可以打破,如果这是你真正想要的。 在for循环尝试从列表中获取下一个项目之前,不会抛出exception。

但我发现最简单的方法是创建并遍历列表副本,这样您就不用担心了。

 foreach(var item in list.ToList()) 

与更复杂代码的可维护性成本相比,额外的未触及列表的额外性能开销通常可以忽略不计。

如果不知道正在进行哪种编辑,很难提供有用的建议。 但是,我发现的模式具有最通用的值,只是构造一个新的列表。

例如,如果您需要查看每个项目并决定是删除它,保持原样,还是在它之后插入项目,您可以使用如下模式:

 IEnumerable butcherTheList(IEnumerable input) { foreach (string current in input) { if(case1(current)) { yield return current; } else if(case2(current)) { yield return current; yield return someFunc(current); } // default behavior is to yield nothing, effectively removing the item } } List newList = butcherTheList(input).ToList();