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

我有点坚持如何做到这一点。


更新:我解决了这个问题。如果我不在continue;while 循环上调用 a,我忽略了我需要处理其他东西的事实。

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

4

6 回答 6

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();
   }
}
于 2011-07-15T16:40:27.740 回答
6
while (something)
{
   foreach (var x in xs)
   {
       if (something is true)
       {
           //Break out of this foreach
           //AND "continue;" on the while loop.
           break;
       }
   }
}
于 2011-07-15T16:04:21.770 回答
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.
   }
}
于 2011-07-15T16:18:07.143 回答
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通过嵌套结构进行传播,这种代码就会经常发生。是否是代码异味还有待商榷:-)

于 2011-07-15T16:12:10.060 回答
0
while (something)
{
   foreach (var x in xs)
   {
       if (something is true)
       {
           break;
       }
   }
}

但是,这两个值不总是等于 true 吗?

于 2011-07-15T16:11:17.757 回答
0

所以你想打破后继续?

while (something)
{
    bool hit = false;

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

    if(hit)
        continue;
}
于 2011-07-15T16:12:37.177 回答