2014-09-05 159 views
2

我在While循環中逐行讀取文本文件。當我到達特定的行時,我想跳過當前和下一個3次迭代。如何在while循環中跳過多個迭代

我想我可以用計數器和類似的東西來做。但我想知道是否有更優雅的方式?

using (var sr = new StreamReader(source)) 
{ 
    string line; 
    while ((line = sr.ReadLine()) != null) 
    { 
     if (line == "Section 1-1") 
     { 
      // skip the next 3 iterations (lines) 
     } 
    } 
} 
+3

在if子句中執行3次ReadLines,每次檢查爲空 – HugoRune 2014-09-05 18:06:24

+0

@HugoRune謝謝,現在這就是我所說的優雅。 – Vahid 2014-09-05 18:10:25

+1

只讀了3更多的行,但不使用這些行 – Chris 2014-09-05 18:10:52

回答

4

有一個for循環執行sr.ReadLine 3次,丟棄的結果,如:

using (var sr = new StreamReader(source)) 
{ 
    string line; 
    while ((line = sr.ReadLine()) != null) 
    { 
     if (line == "Section 1-1") 
     { 
      for (int i = 0; i < 3; i++) 
      { 
       sr.ReadLine(); 
      } 
     } 
    } 
} 

您應該檢查返回sr.ReadLinenull如果流已經走到了盡頭。

+1

謝謝哈比卜,這是我尋找的簡單和優雅的答案。我想我不需要在我的情況下檢查'null'。 – Vahid 2014-09-05 18:14:05

+1

@Vahid,歡迎你 – Habib 2014-09-05 18:20:44

1

讓自己,丟棄線(DiscardLines)的給定數量的功能,並使用它:

string line; 
while ((line = sr.ReadLine()) != null) 
{ 
    if (line == "Section 1-1") 
    { 
     DiscardLines(sr, 3); 
    } 
} 

這令主循環非常簡單。該計數器現在隱藏在DiscardLines中。

1
using (var sr = new StreamReader(source)) 
{ 
    string line; 
    int linesToSkip = 0; 
    while ((line = sr.ReadLine()) != null) 
    { 
     if (linesToSkip > 0) 
     { 
      linesToSkip -= 1; 
      continue; 
     } 
     if (line == "Section 1-1") 
     { 
      // skip the next 3 iterations (lines) 
      linesToSkip = 3; 
     } 
    } 
} 
+0

感謝Zer0的回答,我+1你,但正如我在問題中所述,我試圖避免一個'counter'。 – Vahid 2014-09-05 18:15:25

2

您可以使用File.ReadAllLines與方法extesions:

public static IEnumerable<string> SkipLines(string file, string line, int count) 
{ 
    var enumerable = File.ReadLines(file).GetEnumerator(); 
    while (enumerable.MoveNext()) 
    { 
     var currentLine = enumerable.Current; 
     if (currentLine == line) 
     { 
      var currentCount = 0; 
      while(enumerable.MoveNext() && currentCount < count) 
      { 
        currentCount += 1; 
      } 
     } 

     yield return currentLine; 
    } 
} 

用法:

foreach (var line in SkipLines(source, "Section 1-1", 3)) 
{ 
    // your line 
} 

請記住:ReadLines是懶惰 - 不是所有的線路都加載到內存中一次。

+0

感謝pwas,這比'ReadLine()'快嗎?我的文本文件有點巨大。大約100,000條線。 – Vahid 2014-09-05 18:12:26

+1

你從哪裏得到'MoveNext'?我沒有在'string []'下看到它。 – gunr2171 2014-09-05 18:12:43

+0

@ gunr2171謝謝!我爲你寫了錯誤的方法名稱 - 它是'ReadLines'而不是'ReadAllLines' :) +1。 – 2014-09-05 18:14:49