2012-02-05 51 views
2

我有这样的代码:我怎样才能继续上面的圈

foreach(int i in Directions) 
     { 
      if (IsDowner(i)) 
      { 
       while (IsDowner(i)) 
       { 
        continue; 
        //if (i >= Directions.Count) 
        //{ 
        // break; 
        //} 
       } 

       //if (i >= Directions.Count) 
       //{ 
       // break; 
       //} 

       if (IsForward(i)) 
       { 

         continue; 
         //if (i >= Directions.Count) 
         //{ 
         // break; 
         //} 

        //check = true; 
       } 

       //if (i >= Directions.Count) 
       //{ 
       // break; 
       //} 

       if (IsUpper(i)) 
       { 
         //if (i >= Directions.Count) 
         //{ 
         // break; 
         //} 
        num++; 
        //check = false; 
       } 

       //if (check) 
       //{ 
       // num++; 
       //} 
      } 
     } 

,但我希望有continueforeachwhile循环。我怎样才能做到这一点?

+0

相关:http://stackoverflow.com/questions/8497247/break-nested-loops – CodesInChaos 2012-02-05 10:03:42

回答

6

你可以breakwhile循环,转移到外foreach循环的下一次迭代将开始一个新的while循环:如果您在while循环后有一些其他的代码

foreach(int i in Directions) 
{ 
    while (IsDowner(i)) 
    { 
     break; 
    } 
} 

那你不希望在这种情况下执行,你可以使用一个布尔变量,它将在跳出while循环之前设置,以便此代码不会执行并自动跳转到forach循环的下一次迭代中:

foreach(int i in Directions) 
{ 
    bool broken = false; 
    while (IsDowner(i)) 
    { 
     // if some condition => 
     broken = true; 
     break; 
    } 

    if (broken) 
    { 
     // we have broken out of the inner while loop 
     // and we don't want to execute the code afterwards 
     // so we are continuing on the next iteration of the 
     // outer foreach loop 
     continue; 
    } 

    // execute some other code 
} 
+0

但我有while循环后的另一个代码,我想要他们和下一个foreach变量(我)。 – 2012-02-05 09:55:39

+0

@ahmadalishafiee,你可以使用布尔变量。 – 2012-02-05 09:56:53

+0

编辑的问题。但用你的方式有很多嵌套,如果在我的代码 – 2012-02-05 09:57:03

5

您不能从内部循环继续外部循环。 你有两个选择:

  1. 坏一个:打破了之前的内环设置一个布尔标志,然后检查这个标志,并继续将其设置。

  2. 好的一个:只需将你的大型代码重构为一组函数,这样就没有内部循环。

4

在我看来,使用转到是复杂的嵌套循环中合理的(你是否应该避免使用复杂的嵌套循环是一个不同的问题)。

你可以这样做:

foreach(int i in Directions) 
{ 
    while (IsDowner(i)) 
    { 
     goto continueMainLoop; 
    } 
    //There be code here 
continueMainLoop: 
} 

只是要小心,如果其他人要处理的代码,确保他们不会转到恐惧症。

0

,你可以尝试使用谓词内像循环:

foreach (item it in firstList) 
    { 
     if (2ndList.Exists(x => it.Name.StartsWith(x))) //use predicate instead of for loop. 
      { 
       continue; 
      } 
    } 

希望这有助于你。