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)
只需更改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循环的索引通常表明你做错了什么.
| 归档时间: |
|
| 查看次数: |
12707 次 |
| 最近记录: |