如果我有一个嵌套在另一个循环中的for循环,我如何才能以最快的方式有效地从两个循环(内部和外部)中出来?
我不想必须使用布尔值然后必须说转到另一个方法,而只是在外部循环之后执行第一行代码。
有什么又快又好的方法呢?
我在想异常并不便宜/只应该在真正异常的情况下抛出等等。因此,从性能的角度来看,我不认为这个解决方案是好的。
我不认为利用。net中的新特性(anon方法)来做一些非常基础的事情是正确的。
如果我有一个嵌套在另一个循环中的for循环,我如何才能以最快的方式有效地从两个循环(内部和外部)中出来?
我不想必须使用布尔值然后必须说转到另一个方法,而只是在外部循环之后执行第一行代码。
有什么又快又好的方法呢?
我在想异常并不便宜/只应该在真正异常的情况下抛出等等。因此,从性能的角度来看,我不认为这个解决方案是好的。
我不认为利用。net中的新特性(anon方法)来做一些非常基础的事情是正确的。
当前回答
可以使用循环中的自定义条件来打破循环,从而允许有干净的代码。
static void Main(string[] args)
{
bool isBreak = false;
for (int i = 0; ConditionLoop(isBreak, i, 500); i++)
{
Console.WriteLine($"External loop iteration {i}");
for (int j = 0; ConditionLoop(isBreak, j, 500); j++)
{
Console.WriteLine($"Inner loop iteration {j}");
// This code is only to produce the break.
if (j > 3)
{
isBreak = true;
}
}
Console.WriteLine("The code after the inner loop will be executed when breaks");
}
Console.ReadKey();
}
private static bool ConditionLoop(bool isBreak, int i, int maxIterations) => i < maxIterations && !isBreak;
在这段代码中,我们包含以下输出:
外部循环迭代0 内循环迭代0 内循环迭代1 内循环迭代2 内循环迭代3 内循环迭代4 内部循环之后的代码将在中断时执行
其他回答
人们经常忘记for循环的第二个语句本身就是中断条件,所以在代码中没有必要有额外的if。
这样做是可行的:
bool run = true;
int finalx = 0;
int finaly = 0;
for (int x = 0; x < 100 && run; x++)
{
finalx = x;
for (int y = 0; y < 100 && run; y++)
{
finaly = y;
if (x == 10 && y == 50) { run = false; }
}
}
Console.WriteLine("x: " + finalx + " y: " + finaly); // outputs 'x: 10 y: 50'
我见过很多用break的例子,但没有一个用continue的。
它仍然需要在内部循环中使用某种标志:
while( some_condition )
{
// outer loop stuff
...
bool get_out = false;
for(...)
{
// inner loop stuff
...
get_out = true;
break;
}
if( get_out )
{
some_condition=false;
continue;
}
// more out loop stuff
...
}
抛出一个自定义异常,该异常进入外循环。
它适用于for,foreach或while或任何类型的循环以及任何使用try catch异常块的语言
try
{
foreach (object o in list)
{
foreach (object another in otherList)
{
// ... some stuff here
if (condition)
{
throw new CustomExcpetion();
}
}
}
}
catch (CustomException)
{
// log
}
最干净、最短、最可重用的方法是自调用匿名函数:
没有转到 没有标签 没有临时变量 没有命名函数
用匿名方法,比上面的答案短一行。
new Action(() =>
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits self invoked lambda expression
}
}
})();
Console.WriteLine("Hi");
结束双循环最简单的方法是直接结束第一个循环
string TestStr = "The frog jumped over the hill";
char[] KillChar = {'w', 'l'};
for(int i = 0; i < TestStr.Length; i++)
{
for(int E = 0; E < KillChar.Length; E++)
{
if(KillChar[E] == TestStr[i])
{
i = TestStr.Length; //Ends First Loop
break; //Ends Second Loop
}
}
}