C# - foreach loop within while loop - break out of foreach and continue on the while loop right away?

myermian picture myermian · Jul 15, 2011 · Viewed 9.1k times · Source
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.
}

I'm a bit stuck on how to do this.


Update: I fixed the question. I left out the fact that I need to process other stuff if I don't call a continue; on the while loop.

Sorry, I didn't realize I used the word "something" twice.

Answer

Eric Lippert picture Eric Lippert · Jul 15, 2011

I would rewrite this:

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();
}

as

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();
   }
}