score:6

Accepted answer

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

score:4

LINQ style:

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

score:10

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

score:-1

May you interest this mix :)

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

Related Articles