Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

So how can I restart the loop and change the starting line(getting different key from the array)?

like image 550
Kirev Avatar asked May 28 '12 16:05

Kirev


2 Answers

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.

int i = 0;
while(i < newData.Length) 
{
    if (//Condition)
    {
       //do something with the first line
       i++;
    }
    else
    {
        i = 1;
    }
}
like image 150
Binary Worrier Avatar answered Oct 04 '22 23:10

Binary Worrier


Just change the index of the for loop:

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.

like image 33
gdoron is supporting Monica Avatar answered Oct 04 '22 22:10

gdoron is supporting Monica