开发者

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 "s开发者_开发百科omething" twice.


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


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


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


This should address your requirement:

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

This sort of code happens frequently as soon as you need break to propagate through nested constructs. Whether it is a code smell or not is up for debate :-)


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

however, wouldn't both of these values always equate to true???


So you want to continue after breaking?

while (something)
{
    bool hit = false;

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

    if(hit)
        continue;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜