c#restart for循环

时间:2012-05-28 16:15:19

标签: c# for-loop restart

所以我有这几行代码:

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循环,它将从第一行开始。

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

5 个答案:

答案 0 :(得分:10)

我认为for loop在这里是错误的循环类型,它没有正确表达循环的意图,并且肯定会告诉我你不会搞砸计数器。

int i = 0;
while(i < newData.Length) 
{
    if (//Condition)
    {
       //do something with the first line
       i++;
    }
    else
    {
        i = 1;
    }
}

答案 1 :(得分:8)

只需更改for循环的index

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循环的索引通常表示你做错了。

答案 2 :(得分:4)

只需在i = 0声明中设置else即可;然后,循环声明中的i++应将其设置为1,从而跳过第一行。

答案 3 :(得分: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;
    }
}

答案 4 :(得分: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;
    }
}