我正在循环一系列字符串,例如(1/12/1992苹果卡车12/10/10橙色自行车).数组的长度总是可以被3整除.我需要循环遍历数组并抓住前3个项目(我要将它们插入到数据库中),然后抓住接下来的3个,依此类推,直到所有他们已经走了.
//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.
}
Run Code Online (Sandbox Code Playgroud)
Hen*_*man 24
i每步增加3:
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
}
Run Code Online (Sandbox Code Playgroud)
要回答一些注释,它是 theData.Length3的倍数,因此不需要检查theData.Length-2作为上限.这只会掩盖先决条件中的错误.
i++是循环的标准用法,但不是唯一的方法.尝试每次递增3:
for (int i = 0; i < theData.Length - 2; i+=3)
{
// use theData[i], theData[i+1], theData[i+2]
}
Run Code Online (Sandbox Code Playgroud)