簡體   English   中英

c#restart for循環

[英]c# restart for loop

所以我有這幾行代碼:

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

我已經嘗試過使用 goto,但正如您所看到的,如果我再次啟動 for 循環,它將從第一行開始。

那么如何重新啟動循環並更改起始行(從數組中獲取不同的鍵)?

我認為這里的for loop是錯誤的循環類型,它沒有正確表達循環的意圖,並且肯定會向我建議您不要弄亂計數器。

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

只需更改 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;
    }
}

請注意,這看起來像一個出色的意大利面條式代碼……更改 for 循環的索引通常表明您做錯了什么。

只需在else語句中設置i = 0 然后循環聲明中的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;
    }
}

您只需重置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