C# looping through an array

后端 未结 7 2127
一生所求
一生所求 2021-01-07 20:16

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

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-07 20:33

    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
      }
    

    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.

提交回复
热议问题