C# - while循环中的foreach循环 - 打破foreach并立即继续while循环?

时间:2011-07-15 16:03:29

标签: c# for-loop while-loop break continue

while (foo() == true)
{
   foreach (var x in xs)
   {
       if (bar(x) == true)
       {
           //"break;" out of this foreach
           //AND "continue;" on the while loop.
       }
   }

   //If I didn't continue, do other stuff.
}

我对如何做到这一点有点困惑。


更新:我修正了问题。如果我不在while循环上调用continue;,我就省略了我需要处理其他内容的事实。

抱歉,我没有意识到我曾两次使用“某事”这个词。

6 个答案:

答案 0 :(得分:14)

我会改写这个:

while (foo() == true)
{
   foreach (var x in xs)
   {
       if (bar(x) == true)
       {
           //"break;" out of this foreach
           //AND "continue;" on the while loop.
       }
   }

   //If I didn't continue, do other stuff.
   DoStuff();
}

作为

while (foo()) // eliminate redundant comparison to "true".
{
   // Eliminate unnecessary loop; the loop is just 
   // for checking to see if any member of xs matches predicate bar, so
   // just see if any member of xs matches predicate bar!
   if (!xs.Any(bar))        
   {
       DoStuff();
   }
}

答案 1 :(得分:6)

while (something)
{
   foreach (var x in xs)
   {
       if (something is true)
       {
           //Break out of this foreach
           //AND "continue;" on the while loop.
           break;
       }
   }
}

答案 2 :(得分:3)

如果我理解正确,您可以在此处使用LINQ Any / All谓词:

while (something)
{
    // You can also write this with the Enumerable.All method
   if(!xs.Any(x => somePredicate(x))
   {
      // Place code meant for the "If I didn't continue, do other stuff."
      // block here.
   }
}

答案 3 :(得分:2)

这应该符合您的要求:

while (something)
{   
    bool doContinue = false;

    foreach (var x in xs)   
    {       
        if (something is true)       
        {           
            //Break out of this foreach           
            //AND "continue;" on the while loop.          
            doContinue = true; 
            break;       
        }   
    }

    if (doContinue)
        continue;

    // Additional items.
}

只要您需要break通过嵌套构造传播,就会经常发生这种代码。无论是否有代码味道都有争议: - )

答案 4 :(得分:0)

while (something)
{
   foreach (var x in xs)
   {
       if (something is true)
       {
           break;
       }
   }
}

然而,这两个值都不会总是等于真的???

答案 5 :(得分:0)

所以你想在打破之后继续?

while (something)
{
    bool hit = false;

    foreach (var x in xs)
    {
        if (something is true)
        {
            hit = true;
            break;
        }
    }

    if(hit)
        continue;
}