Skip lines in the file; general extension methods

Is there a better way to write this extension method?

public static class StreamReaderExtensions
{
    public static StreamReader SkipLines(this StreamReader reader, int lines)
    {
        for (var i = 0; i < lines; i++)
        {
            reader.ReadLine();
        }

        return reader;
    }
}

I thought something like:

int linesToSkip = 3;
linesToSkip.Do(reader => reader.ReadLine());

Or:

int linesToSkip = 3;
linesToSkip.Do(() => reader.ReadLine());

But what would it look like Do()?

+3
source share
2 answers

Try using the power already defined in LINQ. Use this extension method to read lines:

public static IEnumerable<string> ReadLines(this StreamReader reader)
{
    while (!reader.EndOfStream)
    {
        yield return reader.ReadLine();
    }
}

Then, if you have open StreamReader, your code might look like this:

int linesToSkip = 3;
var lines = reader.ReadLines().Skip(linesToSkip);

Enjoy.

+7
source

Take a look at this article from Eric Lippert.

He gives this example to implement such an extension:

public static class FileUtilities
{
    public static IEnumerable<string> Lines(string filename)
    {
        if (filename == null)
            throw new ArgumentNullException("filename");
        return LinesCore(filename);
    }

    private static IEnumerable<string> LinesCore(string filename)
    {
        Debug.Assert(filename != null);
        using(var reader = new StreamReader(filename))
        {
            while (true)
            { 
                string line = reader.ReadLine();
                if (line == null) 
                   yield break;
                yield return line;
            }
        }
    }
}

, LINQ, , Skip(), SkipWhile(), TakeWhile() ..

0

Source: https://habr.com/ru/post/1769084/


All Articles