简体   繁体   English

c#restart for循环

[英]c# restart for loop

So I have these few lines of code:所以我有这几行代码:

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

I've tried with goto, but as you can see, if I start the for loop again, it'll start from the first line.我已经尝试过使用 goto,但正如您所看到的,如果我再次启动 for 循环,它将从第一行开始。

So how can I restart the loop and change the starting line(getting different key from the array)?那么如何重新启动循环并更改起始行(从数组中获取不同的键)?

I'd argue that a for loop is the wrong type of loop here, it doesn't correctly express the intent of the loop, and would definitely suggest to me that you're not going to mess with the counter.我认为这里的for loop是错误的循环类型,它没有正确表达循环的意图,并且肯定会向我建议您不要弄乱计数器。

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

Just change the index of the for loop:只需更改 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;
    }
}

Note that this looks like an excellent spaghetti code... Changing the index of a for loop usually indicate that you're doing something wrong.请注意,这看起来像一个出色的意大利面条式代码……更改 for 循环的索引通常表明您做错了什么。

Just set i = 0 in your else statement;只需在else语句中设置i = 0 the i++ in the loop declaration should then set it to 1 and thus skip the first line.然后循环声明中的i++应将其设置为1 ,从而跳过第一行。

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;
    }
}

You would just reset i and resize the array您只需重置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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM