如果我有一个嵌套在另一个循环中的for循环,我如何才能以最快的方式有效地从两个循环(内部和外部)中出来?

我不想必须使用布尔值然后必须说转到另一个方法,而只是在外部循环之后执行第一行代码。

有什么又快又好的方法呢?

我在想异常并不便宜/只应该在真正异常的情况下抛出等等。因此,从性能的角度来看,我不认为这个解决方案是好的。

我不认为利用。net中的新特性(anon方法)来做一些非常基础的事情是正确的。


当前回答

我就设个旗子。

var breakOuterLoop = false;
for (int i = 0; i < 30; i++)
{
    for (int j = 0; j < 30; j++)
    {
        if (condition)
        {
            breakOuterLoop = true;
            break;
        }
    }
    if (breakOuterLoop){
        break;
    }
}

其他回答

考虑到函数/方法并使用早期返回,或将循环重新安排为while子句。Goto /exceptions/无论什么在这里肯定不合适。

def do_until_equal():
  foreach a:
    foreach b:
      if a==b: return

抛出一个自定义异常,该异常进入外循环。

它适用于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 
}

人们经常忘记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'

这里没有提到的另一种方法是将双循环合并为产品上的单个循环,它既干净又不依赖于更新的。net特性。然后在循环内部,计数器的值可以使用简单的数学计算:

int n; //set to max of first loop
int m; //set to max of second loop

for (int k = 0; k < n * m; k++)
{
    //calculate the values of i and j as if there was a double loop
    int i = k / m;
    int j = k % m;
    
    if(exitCondition)
    {
        break;
    }
}
         bool breakInnerLoop=false
        for(int i=0;i<=10;i++)
        {
          for(int J=0;i<=10;i++)
          {
              if(i<=j)
                {
                    breakInnerLoop=true;
                    break;
                }
          }
            if(breakInnerLoop)
            {
            continue
            }
        }