Rushabh Shah
Rushabh Shah

Reputation: 287

Read first 10 line from file using LINQ

Can anyone explain how to read first 10 lines from the text file in LINQ.

Code using StreamReader:

using (var reader = new StreamReader(fileName))
{
    string ListLines = "";
    for (int i = 0; i < 10; i++)
    {
        ListLines[i] = reader.ReadLine();
    }
}
return ListLines;

Upvotes: 3

Views: 8675

Answers (4)

abatishchev
abatishchev

Reputation: 100278

Your code is already optimal to achieve the goal:

var list = new List<string>();
using (var reader = new StreamReader(fileName))
{
    for (int i = 0; i < 10; i++)
    {
        list.Add(reader.ReadLine());
    }
}
return list;

or

using (var reader = new StreamReader(fileName))
{
    for (int i = 0; i < 10; i++)
    {
        yield return reader.ReadLine();
    }
}

or

var r = File.ReadLines(fileName)
            .Take(10)   // limit to first 10
            .ToArray(); // materialize, if needed

Upvotes: 6

cuongle
cuongle

Reputation: 75306

LINQ style:

using (var textReader = File.OpenText(fileName))
{
    return Enumerable.Range(1, 10).Select(i => textReader.ReadLine());
}

Upvotes: 5

purplesoft
purplesoft

Reputation: 526

May you interest this mix :)

using (var reader = new StreamReader(filename))
{
    return (from p in Enumerable.Range(0, 10) select reader.ReadLine()).ToList();
}

Upvotes: -1

Servy
Servy

Reputation: 203828

You can use:

var lines = File.ReadLines(path).Take(10));

By using ReadLines, rather than ReadAllLines you will stream data from the file, rather than reading the entire thing into memory. If you are still on C# 3.5, not 4 (when ReadLines was added) you can use the below implementation:

public static IEnumerable<string> ReadLines(string filename)
{
    using (TextReader tr = new StreamReader(filename))
    {
        string nextLine = tr.ReadLine();

        while (nextLine != null)
        {
            yield return nextLine;
            nextLine = tr.ReadLine();
        }
    }
}

Upvotes: 10

Related Questions