打破内部foreach循环并继续外部foreach循环

如果我有一个嵌套的foreach循环,我怎么做打破内循环并告诉外部继续在那一点没有在内循环下面做任何其他代码?

foreach(var item in items) { foreach(var otheritem in otheritems) { if (!double.TryParse(otheritem)) { //break inner loop //continue outer loop so we never get to DoStuff() } } DoStuff(); } 

用国旗怎么样?

 foreach(var item in items) { bool flag = false; foreach(var otheritem in otheritems) { if (!double.TryParse(otheritem)) { flag = true; break; } } if(flag) continue; DoStuff(); } 
 foreach(var item in items) { foreach(var otheritem in otheritems) { if (!double.TryParse(otheritem)) { //... goto nextUpperLoop; } } DoStuff(); nextUpperLoop: ; } 

首先编写一个更好的Double.TryParse版本:

 static double? TryParseDouble(this string s) { double d; return double.TryParse(s, out d) ? (double?)d : (double?)null; } 

好的,现在你有一些东西可以很容易地用来完全消除内环,所以问题就消失了:

 foreach(var item in items) if (!otheritems.Any(otherItem=>otherItem.TryParseDouble() == null)) DoStuff(); 

而不是试图弄清楚如何移动控制, 只需编写看起来像逻辑的代码 。 如果逻辑是“如果任何其他项不解析为双精度,则不执行操作”,则使用Any谓词测试所有其他项,以查看它们中的任何项是否不解析为双精度数。 没有循环,因此不需要花哨的循环控制。

我倾向于更进一步; 捕获查询中的逻辑,然后迭代查询:

 var goodItems = from item in items where !item.OtherItems.Any(otherItem=>otherItem.TryParseDouble() == null)) select item; foreach(var goodItem in goodItems) DoStuff(goodItem); 

简单就是最好的……

  bool doStuff = true; foreach(var otheritem in otheritems) { if (!double.TryParse(otheritem)) { doStuff = false; break; } } if(doStuff) DoStuff(); 

另一种方法是重构:

 foreach(var outerItem in outerLoop) { Foo(outerItem); } ... void Foo(OuterItem item) { foreach(var innerItem in innerLoop) { if(someTest) return; } DoStuff(); } 

return确保DoStuff不会发生。

你需要一个变量来控制,就像你说的那样……做一个break

 bool doStuff = true; foreach(var item in items) { doStuff = true; foreach(var otheritem in otheritems) { if (!double.TryParse(otheritem)) { doStuff = false; break; } } if (doStuff) DoStuff(); } 
 foreach(var item in items) { var shouldContinue = false; foreach(var otheritem in otheritems) { if (!double.TryParse(otheritem)) { shouldContinue = true; //break inner loop //continue outer loop so we never get to DoStuff() } } if(shouldContinue) continue; DoStuff(); } 

Iircrest一下; 语句只会打破最接近的循环,所以发出一个中断; 在内循环中应该继续外循环上的下一个项目。

从你的代码片段中不清楚,但如果你只需要在其他项目中寻找不可解析的值,那么你可以使用LINQ:

 foreach(var item in items) { bool shouldISkip = otheritems.Any(otherItem => !double.TryParse(otherItem)); if(shouldISkip) continue; DoStuff(); }