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

m-y*_*m-y 6 c# for-loop continue break while-loop

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.
}
Run Code Online (Sandbox Code Playgroud)

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


更新:我修正了问题.我遗漏了一个事实,即如果我不在continue;while循环上调用,我需要处理其他内容.

对不起,我没有意识到我曾两次使用"某事"这个词.

Eri*_*ert 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();
}
Run Code Online (Sandbox Code Playgroud)

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();
   }
}
Run Code Online (Sandbox Code Playgroud)

  • @myermian:我尝试使用的一个很好的经验法则:如果一个循环用于*一遍又一遍地执行特定的副作用*,那么使用循环.如果循环仅用于*计算值*,则将循环移动到辅助函数中,或者找到已经执行了所需操作的辅助函数 - 如"Any","All"或"Sum",或者随你.这样,您就可以使循环成为辅助程序的实现细节,而不是方法的嵌套控制流. (4认同)

adr*_*nos 6

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


Ani*_*Ani 4

如果我理解正确,您可以在此处使用 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.
   }
}
Run Code Online (Sandbox Code Playgroud)