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を呼び出さない場合は、他のものを処理する必要があるという事実を省略しました。

申し訳ありませんが、「何か」という言葉を2回使用したことに気づきませんでした。

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 に答える