2014-03-31 43 views
-4

如何在突出顯示的行中分解兩個for循環。如何分解兩個循環

bool conditionitem = true; 

for (int cun = 0; cun < ItemIdNumber.Length; cun++) 
{ 
    int Item_Id = Convert.ToInt32(ItemIdNumber[cun]); 

    for (int yyu = 0; yyu <= 1258038; yyu++) 
    { 
     int weer = c[yyu]; 

     if (weer == Item_Id) 
     { 
      conditionitem = false; 
      itemseq = yyu; 
     } 
    } 

    if (conditionitem != false) 
    { 
     MessageBox.Show("THE ITEM ID DOES NOT EXIST.!"); 
     break; //--> here i want two break for two times 
    } 
} 

通過該(表示MessageBox.Show("THE ITEM ID DOES NOT EXIST.!");之後)打破它僅破壞第一回路。

+1

重複:http://stackoverflow.com/questions/324831/breaking-out-of-a-nested-loop –

+0

可能重複[如何從雙/嵌套循環中的主/外循環?]( http://stackoverflow.com/questions/13073300/how-to-break-from-main-outer-loop-in-a-double-nested-loop) – rpax

+6

我不明白這一點,你已經在外面循環。 –

回答

0

把你的嵌套循環放入一個函數,並且每當你想打破循環時返回true/false?

bool Function() 
{ 
    for(int i = 0; i < 10; ++i) 
    { 
     for(int j = 0; j < 10; ++j) 
     { 
      if (error) 
      { 
       MessageBox.Show("THE ITEM ID DOES NOT EXIST.!"); 
       return false; 
      } 
     } 
    } 
    return true; 
} 
1

兩個選項,我能想到的:

(1)將第二循環中一個標誌,你跳出來了。如果設置了標誌,則按照內部迭代執行第一次迭代的條件。

bool flag = false; 
foreach (item in Items) 
{ 
    foreach (item2 in Items2) 
    { 
     flag = true; // whenever you want to break 
     break; 
    } 

if (flag) break; 
} 

(2)使用goto語句。

foreach (item in Items) 
    { 
    foreach (item2 in Items2) 
    { 
     goto GetMeOutOfHere: // when you want to break out of both 
    } 

    } 

    GetMeOutOfHere: 
     // do what you want to do. 
+0

* goto *並不歡迎。我大力推薦它,其中大部分(是的,也有例外)它表明了不好的編碼風格。 – BudBrot

1

可以重構環路是找到項目的方法:

SomeType SomeMethod(int itemId) 
{ 
    for (int cun = 0; cun < ItemIdNumber.Length; cun++) 
    { 
     int Item_Id = Convert.ToInt32(ItemIdNumber[cun]); 

     for (int yyu = 0; yyu <= 1258038; yyu++) 
     {   
      if (c[yyu] == itemId) return yyu; 
     } 
    } 
    return null; 
} 

然後,只需使用:

var item = SomeMethod(Item_Id); 
if(item == null) 
{ 
    MessageBox.Show("THE ITEM ID DOES NOT EXIST.!"); 
} 
else 
{ 
    // ... 
} 

這也避免了混合UI邏輯和內部邏輯。