开发者

Skip lines in file; generic extension methods

开发者 https://www.devze.com 2023-01-20 02:18 出处:网络
Is there a better way to write this extension method? public static class StreamReaderExtensions { public static StreamReader SkipLines(this StreamReader reader, int lines)

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;
    }
}开发者_JS百科

I was thinking something like:

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

Or:

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

But what would Do() look like?


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

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

Then, given you have an open StreamReader, your code can look like this:

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

Enjoy.


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

If have have this functionality just use the normal power of LINQ by using things like Skip(), SkipWhile(), TakeWhile(), etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号