7

所以我有这几行代码:

string[] newData = File.ReadAllLines(fileName)
int length = newData.Length;
for (int i = 0; i < length; i++)
{
    if (Condition)
    {
       //do something with the first line
    }
    else
    {
      //restart the for loop BUT skip first line and start reading from the second
    }
}

我已经尝试过使用 goto,但是正如您所看到的,如果我再次启动 for 循环,它将从第一行开始。

那么如何重新启动循环并更改起始行(从数组中获取不同的键)?

4

5 回答 5

12

我认为 afor loop在这里是错误的循环类型,它没有正确表达循环的意图,并且肯定会向我建议您不会弄乱计数器。

int i = 0;
while(i < newData.Length) 
{
    if (//Condition)
    {
       //do something with the first line
       i++;
    }
    else
    {
        i = 1;
    }
}
于 2012-05-28T16:18:37.183 回答
8

只需更改indexfor 循环的:

for (int i = 0; i < newData.Length; i++) // < instead of <= as @Rawling commented.
{
    if (//Condition)
    {
       //do something with the first line
    }
    else
    {
      // Change the loop index to zero, so plus the increment in the next 
      // iteration, the index will be 1 => the second element.
      i = 0;
    }
}

请注意,这看起来像是一个出色的意大利面条代码...更改 for 循环的索引通常表明您做错了什么。

于 2012-05-28T16:17:07.847 回答
4

只需i = 0在您的else声明中设置;然后i++in 循环声明应将其设置为1并因此跳过第一行。

于 2012-05-28T16:17:21.653 回答
0
string[] newData = File.ReadAllLines(fileName)

for (int i = 0; i <= newData.Length; i++)
{
    if (//Condition)
    {
       //do something with the first line
    }
    else
    {
      //restart the for loop BUT skip first line and start reading from the second
      i = 0;
    }
}
于 2012-05-28T16:18:07.183 回答
0

您只需重置i并调整数组大小

int length = newData.Length; // never computer on each iteration
for (int i = 0; i < length; i++)
{
    if (condition)
    {
       //do something with the first line
    }
    else
    {
      // Resize array
      string[] newarr = new string[length - 1 - i];
      /*
       * public static void Copy(
       *    Array sourceArray,
       *    int sourceIndex,
       *    Array destinationArray,
       *    int destinationIndex,
       *    int length
       * )
       */
      System.Array.Copy(newData, i, newarr, 0, newarr.Length); // if this doesn't work, try `i+1` or `i-1`
      // Set array
      newData = newarr;
      // Restart loop
      i = 0;
    }
}
于 2012-05-28T16:20:45.533 回答