2013-06-19 14 views
-1

嗨,大家好,如何在foreach中重複一個循環。如何在foreach中重複一個循環

foreach (string line in File.ReadLines("file.txt")) 
{ 
    // now line == "account", next line == "account1" 
    if (line.Contains("a")) 
     //next loop take "account1"; 
    else 
     // need to set that next loop will take line == "account" again 
} 

怎麼辦呢?

+4

你不能;改爲使用'for'。 – Nolonar

+2

這個例子會被卡在一個循環中,反覆閱讀'賬戶'這一行......? –

+0

這看起來像一個XY問題 - http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem。你能解釋一下你的代碼的總體意圖,因爲這個示例看起來很有缺陷嗎? – Kami

回答

4

假設在循環中只有if/else構造,則不需要更改代碼。

if條件的計算結果爲true時,else將不會執行並且循環繼續。

在要立即恢復循環,確保沒有別的以下條件執行時,使用continue語句更加複雜:

continue語句將控制權交給封閉,而下一次迭代,做,爲了,或者在其中出現的foreach語句。

foreach (string line in File.ReadLines("file.txt")) 
{ 
    // now line == "account", next line == "account1" 
    if (line.Contains("a")) 
     continue; 
    else 
     // need to set that next loop will take line == "account" again 

    // more stuff that we don't want to execute if line.Contains("a") 
} 
+0

@Downvoter - 關心提交? – Oded

+0

我沒有downvote,但我不知道這是他想要的。如果else主體是'print line',他可能要多次打印「帳戶」。你需要額外的代碼才能做到這一點。 – nmat

+0

@nmat - 在額外的閱讀中,他似乎想要的是沒有意義的。如果他有他想要的路線,爲什麼不直接操作它並完成它呢? – Oded

1

雖然我不完全理解你的榜樣,我想我明白你的問題。我有同樣的問題,並能夠想出一個解決方案:在foreach中包含一個while循環。在您的例子就應該是這樣的:

foreach (string line in File.ReadLines("file.txt")) 
{ 
    bool repeat = true; 
    while (repeat) 
    { 
     // now line == "account", next line == "account1" 
     if (line.Contains("a")) 
     { 
      //do your logic for a break-out case 
      repeat = false; 
     } 
     else 
     { 
      //do your logic for a repeat case on the same foreach element 
      //in this instance you'll need to add an "a" to the line at some point, to avoid an infinite loop. 
     } 
    } 
} 

我知道我很晚了比賽,但我希望這將是爲別人誰在這裏絆倒同樣的問題很有幫助。

1

我想這可能也是有幫助的,如果別人來

for (int i = 0; i < inventoryTimeBlocks.Count; i++) 
{ 
if (line.Contains("a")) 
    //next loop take "account1"; 
else 
{ 
    if(i > 0) 
    { 
    i = i - 1; 
    continue; 
    } 
} 
}