如何在while循环中跳过多次迭代

本文关键字:迭代 while 循环 | 更新日期: 2023-09-27 18:20:52

我正在While循环中逐行读取文本文件。当我到达一个特定的行时,我想跳过当前和接下来的3次迭代。

我想我可以用计数器之类的东西来做。但我想知道是否还有更优雅的方式?

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

如何在while循环中跳过多次迭代

有一个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.ReadLine是否返回null,或者流是否已结束。

您可以将File.ReadAllLines与方法外显一起使用:

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是惰性的——并不是所有的行都同时加载到内存中。

让自己成为一个放弃给定行数(DiscardLines)并使用它的函数:

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

这使得主循环非常简单。计数器现在隐藏在DiscardLines中。

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