C#学习教程:打破内层foreach循环,继续外层foreach循环在那一点上继续,而不在内循环下面做任何其他代码?foreach(variteminitems){foreach(varotheriteminotheritems){if(!double.TryParse(otheritem)){//打破内部循环//继续外部循环,这样我们就永远不会到达DoStuff()}}DoStuff();使用标志怎么样?foreach(项目中的var项目){boolflag=false;foreach(varotheriteminotheritems){if(!double.TryParse(otheritem)){flag=true;休息;}}如果(标志)继续;做东西();}foreach(variteminitems){foreach(varotheriteminotheritems){if(!double.TryParse(otheritem)){//...gotonextUpperLoop;}}做东西();下一个上循环:;}先写个更ok的Double.TryParse版本:staticdouble?TryParseDouble(这个字符串s){doubled;返回double.TryParse(s,outd)?(双?)d:(双?)空;好的,现在你有了Something可以很容易地用来完全消除内部循环,所以问题就消失了:foreach(variteminitems)if(!otheritems.Any(otherItem=>otherItem.TryParseDouble()==null))多斯图ff();而不是试图弄清楚如何移动控制,只需编写看起来像逻辑的代码如果逻辑是“如果任何其他项目没有解析为双精度,则什么都不做”,使用Any谓词来测试所有其他项目,查看它们中是否有任何一个不解析为双打。没有循环,所以不需要花哨的循环控制。我倾向于更进一步;捕获查询中的逻辑,然后遍历查询:vargoodItems=fromiteminitemswhere!item.OtherItems.Any(otherItem=>otherItem.TryParseDouble()==null))selectitem;foreach(vargoodItemingoodItems)DoStuff(goodItem);简单是最好的...booldoStuff=true;foreach(varotheriteminotheritems){if(!double.TryParse(otheritem)){doStuff=false;休息;}}if(doStuff)DoStuff();另一种方法是重构:foreach(varouterIteminouterLoop){Foo(outerItem);}...voidFoo(OuterItemitem){foreach(varinnerItemininnerLoop){if(someTest)返回;}做东西();}return确保DoStuff不会发生。你需要一个变量来控制,就像你说的……休息一下。布尔doStuff=真;foreach(项目中的可变项目){doStuff=true;foreach(varotheriteminotheritems){if(!double.TryParse(otheritem)){doStuff=false;休息;}}如果(doStuff)DoStuff();}foreach(variteminitems){varshouldContinue=false;foreach(varotheriteminotheritems){if(!double.TryParse(otheritem)){shouldContinue=true;//breakinnerloop//continueouterloop这样我们就永远不会到达DoStuff()}}if(shouldContinue)continue;做东西();}IIrcrest一点;语句只会打破最近的循环,所以发出一个break;在内循环中应该继续外循环中的下一项。从你的代码片段看不清楚,但如果你只是需要在其他项目中寻找无法解析的值,那么你可以使用LINQ:以上就是C#学习教程:打破内层foreach循环并继续外层foreach循环分享了,如果对你有用,需要了解更多C#学习教程,希望大家多多关注—foreach(variteminitems){boolshouldISkip=otheritems.Any(otherItem=>!double.TryParse(otherItem));如果(应该跳过)继续;做东西();}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
