如果我有一个嵌套的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();
}
发布于 2011-11-17 22:19:37
使用标志如何?
foreach(var item in items)
{
bool flag = false;
foreach(var otheritem in otheritems)
{
if (!double.TryParse(otheritem))
{
flag = true;
break;
}
}
if(flag) continue;
DoStuff();
}
发布于 2011-11-17 22:31:32
foreach(var item in items)
{
foreach(var otheritem in otheritems)
{
if (!double.TryParse(otheritem))
{
//...
goto nextUpperLoop;
}
}
DoStuff();
nextUpperLoop: ;
}
发布于 2011-11-17 22:20:12
简单是最好的。
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
不会发生。
https://stackoverflow.com/questions/8168578
复制相似问题