2010-03-09 99 views
11

我正在循環一串字符串,例如(1/12/1992蘋果卡車12/10/10橙色自行車)。數組的長度將總是可以被3整除。我需要遍歷數組並獲取前3個項目(我將它們插入到數據庫中),然後抓取下一個3等等,直到所有他們已經走過了。C#循環訪問數組

//iterate the array 
for (int i = 0; i < theData.Length; i++) 
{ 
    //grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3. 
} 
+3

問題是什麼? – 2010-03-09 20:32:20

+2

5個答案在40秒內相互提交,全部使用相同(幾乎確切)的信息。哈哈。尼斯。 – JasCav 2010-03-09 20:33:12

+2

我發現有趣的是當我寫作我的時候發佈了五個答案......並且*沒有一個答案*獲得了上限。 – 2010-03-09 20:33:30

回答

20

只需3中的每個步驟增加i

Debug.Assert((theData.Length % 3) == 0); // 'theData' will always be divisible by 3 

    for (int i = 0; i < theData.Length; i += 3) 
    { 
     //grab 3 items at a time and do db insert, 
     // continue until all items are gone.. 
     string item1 = theData[i+0]; 
     string item2 = theData[i+1]; 
     string item3 = theData[i+2]; 
     // use the items 
    } 

回答一些意見,這是一個給定的theData.Length是3的倍數,所以沒有需要檢查theData.Length-2作爲上限。這隻會掩蓋前提條件中的錯誤。

+0

好評點您的版本 – Javier 2010-03-09 21:01:13

7

i++是循環的標準使用,但不是唯一的方法。嘗試通過3每次遞增:

for (int i = 0; i < theData.Length - 2; i+=3) 
    { 

     // use theData[i], theData[i+1], theData[i+2] 

    } 
+3

到目前爲止,您是唯一一個在上次迭代中不會出現超出界限錯誤的人;相反,你停止一個簡短的迭代。試試'我 2010-03-09 20:35:34

+0

@ mmyers - 偉大的思想家都認爲。 :)已經改變它。但我不認爲檢查是必要的,只是把它放進去,因爲它似乎是合乎邏輯的... – froadie 2010-03-09 20:36:24

+1

+1對於長度上的檢查! – FrustratedWithFormsDesigner 2010-03-09 20:36:30

3

不太難。僅僅通過3遞增for循環的計數器每次迭代,然後偏移索引,以獲得一批3在同一時間:

for(int i=0; i < theData.Length; i+=3) 
{ 
    var item1 = theData[i]; 
    var item2 = theData[i+1]; 
    var item3 = theData[i+2]; 
} 

如果數組的長度不是garuanteed是三的倍數,您需要使用theData.Length - 2來檢查上限。

2

您的for循環不需要只添加一個循環。你可以循環三次。

for(int i = 0; i < theData.Length; i+=3) 
{ 
    string value1 = theData[i]; 
    string value2 = theData[i+1]; 
    string value3 = theData[i+2]; 
} 

基本上,你只是使用索引來獲取數組中的值。在這裏需要注意的一點是,我不檢查是否超過陣列的末端。確保你正在進行邊界檢查!

+0

Downvote?做什麼的? (我注意到除第一個以外的所有答案都是downvoted。跛腳。) – JasCav 2010-03-09 21:11:34

+0

第一個原本是,但似乎已經取消。奇怪。 – froadie 2010-03-09 21:16:29

1

這應該工作:

//iterate the array 
for (int i = 0; i < theData.Length; i+=3) 
{ 
    //grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3. 
    var a = theData[i]; 
    var b = theData[i + 1]; 
    var c = theData[i + 2]; 
} 

我已經downvoted這個答案一次。我很確定它與使用data.Length作爲upperbound有關。代碼是工作正常,因爲數組保證是問題狀態的三倍。如果這個保證沒有到位,你需要用Data.Length - 2來檢查上限。

1

這裏是一個更通用的解決方案:

int increment = 3; 
for(int i = 0; i < theData.Length; i += increment) 
{ 
    for(int j = 0; j < increment; j++) 
    { 
     if(i+j < theData.Length) { 
     //theData[i + j] for the current index 
     } 
    } 

}