c#restart for循环

Kir*_*rev 6 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Bin*_*ier 10

我认为这for loop是一个错误的循环类型,它没有正确表达循环的意图,并且肯定会向我建议你不要乱用计数器.

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

  • @Henk:我不认为你是在听我的.这两个循环是等价的并不重要(我不在乎),当有人读取代码时,他们可能会忽略`for`版本循环多次而不会将埋藏的变化捕获到` i`.我认为,'while`条件的明显简单性使得它成为读者的标志,以确定它不像它看起来那么简单.恕我直言,`for`版本中的结构不计入深蹲,因为你破坏了`for`和它的结构,打破了`for`最常见的用例. (6认同)
  • 但这只是一个丑陋的格式化循环....同意OP应该购买其他东西虽然. (2认同)
  • 不,这是一个循环.是的,你可以用for循环来做,但我认为它是代码味道.对于_Implies_多次执行某些操作,或执行多个步骤.这不是这个循环的作用. (2认同)

gdo*_*ica 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • `i = 1`,真的吗? (3认同)