修改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())
与更复杂代码的可维护性成本相比,额外的未触及列表的额外性能开销通常可以忽略不计。
如果不知道正在进行哪种编辑,很难提供有用的建议。 但是,我发现的模式具有最通用的值,只是构造一个新的列表。
例如,如果您需要查看每个项目并决定是删除它,保持原样,还是在它之后插入项目,您可以使用如下模式:
上述就是C#学习教程:修改foreach循环内的列表分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
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();
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1027654.html