Vahid
Vahid

Reputation: 5444

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

Upvotes: 2

Views: 1250

Answers (4)

user2160375
user2160375

Reputation:

You can use File.ReadAllLines with method 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;
    }
}

usage:

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

Keep in mind: ReadLines is lazy - not all lines are loaded into memory at once.

Upvotes: 2

Zer0
Zer0

Reputation: 7354

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

Upvotes: 1

Habib
Habib

Reputation: 223267

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.

Upvotes: 4

usr
usr

Reputation: 171178

Make yourself a function that discards a given number of lines (DiscardLines) and use it:

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

That keeps the main loop very simple. The counter is now hidden in DiscardLines.

Upvotes: 1

Related Questions