Ger*_*ald 22 c# foreach loops if-statement while-loop
我有以下代码:
foreach(// Some condition here)
{
while (// Some condition here)
{
foreach (// Some condition here)
{
if (// Condition again)
{
//Do some code
}
if (// Condition again)
{
//Stop the first foreach then go back to first foreach
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是当我if在最后一个foreach循环中点击第二个语句时返回第一个foreach循环.
注意:如果第二个if语句不为真,它应该继续最后一个foreach循环,直到条件不为真.
提前致谢!
Hen*_*man 32
直接的唯一方法是使用a goto.
另一个(更好的)选择是重组,直到问题消失.例如,将内部代码(while + foreach)放在方法中并使用return返回.
Dus*_*san 15
像这样的东西:
resetLoop = false;
for(// Some condition here)
{
while (// Some condition here)
{
foreach (// Some condition here)
{
if (// Condition again)
{
//Do some code
}
if (// Condition again)
{
//Stop the first foreach then go back to first foreach
resetLoop = true;
break;
}
}
if (resetLoop) break;
}
if (resetLoop) {
// Reset for loop to beginning
// For example i = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
没有人提到它(Henk简要提到),但最好的方法是将你的循环移动到自己的方法和使用 return
public ReturnType Loop(args)
{
foreach outerloop
foreach innerLoop
if(Condition)
return;
}
Run Code Online (Sandbox Code Playgroud)
正如我所见,您接受了一个人引用您的goto语句的答案,在现代编程和专家看来goto是一个杀手,我们称它为编程中的杀手,这有某些原因,在此我不再讨论在这一点上,但是您的问题的解决方案非常简单,您可以在这种情况下使用布尔标志,就像我将在示例中演示的那样:
foreach(// Some condition here)
{
//solution
bool breakme = false;
while (// Some condition here)
{
foreach (// Some condition here)
{
if (// Condition again)
{
//Do some code
}
if (// Condition again)
{
//Stop the first foreach then go back to first foreach
breakme = true;
break;
}
}
}
if(breakme)
{
break;
}
}
Run Code Online (Sandbox Code Playgroud)
简单明了。:)
| 归档时间: |
|
| 查看次数: |
16494 次 |
| 最近记录: |