Search code examples
c#while-loopstreamreadercontinue

How to skip multiple iterations in a while loop


I'm reading a text file line by line in a While loop. When I reach a specific line I want to skip the the current and the next 3 iterations.

I guess I can do it using a counter and things like that. But I was wondering if there is a more elegant way?

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

Solution

  • Have a for loop to execute sr.ReadLine 3 times and discard the result like:

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

    You should check for sr.ReadLine returning null or if the stream has come to an end.