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

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

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

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

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


当前回答

您要求的是快速、漂亮、不使用布尔、不使用goto和c#的组合。你已经排除了所有可能的方法去做你想做的事。

最快捷和最不丑陋的方法是使用goto。

其他回答

结束双循环最简单的方法是直接结束第一个循环

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
        }
    }
}

好吧,去吧,但那很难看,而且并不总是可能的。您还可以将循环放入方法(或anon-method)中,并使用return退出回主代码。

    // goto
    for (int i = 0; i < 100; i++)
    {
        for (int j = 0; j < 100; j++)
        {
            goto Foo; // yeuck!
        }
    }
Foo:
    Console.WriteLine("Hi");

vs:

// anon-method
Action work = delegate
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits anon-method
        }
    }
};
work(); // execute anon-method
Console.WriteLine("Hi");

注意,在c# 7中,我们应该得到“局部函数”,这(语法tbd等)意味着它应该像这样工作:

// local function (declared **inside** another method)
void Work()
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits local function
        }
    }
};
Work(); // execute local function
Console.WriteLine("Hi");

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

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

c#自适应的方法经常在C中使用——设置外循环的变量值的循环外条件(即对于循环使用int变量INT_MAX -1通常是很好的选择):

for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 100; j++)
    {
        if (exit_condition)
        {
            // cause the outer loop to break:
            // use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue 
            i = int.MaxValue - 1;
            Console.WriteLine("Hi");
            // break the inner loop
            break;
        }
    }
    // if you have code in outer loop it will execute after break from inner loop    
}

正如代码中的注释所说,break不会神奇地跳转到外循环的下一个迭代-所以如果你的代码在内循环之外,这种方法需要更多的检查。在这种情况下考虑其他解决方案。

这种方法适用于for和while循环,但不适用于foreach。在foreach的情况下,你不会有代码访问隐藏的枚举器,所以你不能改变它(即使你可以IEnumerator没有一些“MoveToEnd”方法)。

内联评论的作者致谢: i = INT_MAX - 1的建议由Meta 对于ygoe的评论。 适当的IntMax由jmbpiano 对内循环后代码的注释

最干净、最短、最可重用的方法是自调用匿名函数:

没有转到 没有标签 没有临时变量 没有命名函数

用匿名方法,比上面的答案短一行。

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");