Search code examples
c#for-loopwhile-loopbreakcontinue

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


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.


Solution

  • If I understand you correctly, you can use the LINQ Any / All predicate here:

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