C # restart for loop

So, I have a 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 tried with goto, but as you can see, if I run the for loop again, it will start on the first line.

So, how can I restart the loop and change the start line (getting another key from the array)?

+6
source share
5 answers

I would say that for loop is the wrong type of loop here, it incorrectly expresses the intent of the loop and will definitely tell me that you are not going to bother with the counter.

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

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 great spaghetti code ... Changing the index of the for loop usually means that you are doing something wrong.

+7
source

Just set i = 0 in your else ; i++ in the loop declaration should then set it to 1 and thus skip the first line.

+4
source
 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; } } 
0
source

You just reset i and resize the array

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

Source: https://habr.com/ru/post/916858/


All Articles