C#遍历数组 [英] C# looping through an array

查看:88
本文介绍了C#遍历数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历一串字符串,例如(1992年1月12日的Apple Truck 12/10/10橙色自行车).数组的长度总是可以被3整除.我需要遍历数组并获取前3个项(我将它们插入数据库),然后获取接下来的3个,依此类推,直到所有他们已经经历了.

I am looping through an array of strings, such as (1/12/1992 apple truck 12/10/10 orange bicycle). The array's length will always be divisible by 3. I need to loop through the array and grab the first 3 items (I'm going to insert them into a DB) and then grab the next 3 and so on and so forth until all of them have been gone through.

//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.
}

推荐答案

在每个步骤中,只需将i递增3:

Just increment i by 3 in each step:

  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作为上限.那只会掩盖先决条件中的错误.

To answer some comments, it is a given that theData.Length is a multiple of 3 so there is no need to check for theData.Length-2 as an upperbound. That would only mask errors in the preconditions.

这篇关于C#遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆