coson
coson

Reputation: 8659

Reading Text Files with LINQ

I have a file that I want to read into an array.

string[] allLines = File.ReadAllLines(@"path to file");

I know that I can iterate through the array and find each line that contains a pattern and display the line number and the line itself.

My question is:

Is it possible to do the same thing with LINQ?

Upvotes: 4

Views: 7718

Answers (3)

Scott Wegner
Scott Wegner

Reputation: 7483

Using LINQ is possible. However, since you want the line number as well, the code will likely be more readable by iterating yourself:

    const string pattern = "foo";
    for (int lineNumber = 1; lineNumber <= allLines.Length; lineNumber++)
    {
        if (allLines[lineNumber-1].Contains(pattern))
        {
            Console.WriteLine("{0}. {1}", lineNumber, allLines[i]);
        }
    }

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160852

Well yes - using the Select() overload that takes an index we can do this by projecting to an anonymous type that contains the line itself as well as its line number:

var targetLines = File.ReadAllLines(@"foo.txt")
                      .Select((x, i) => new { Line = x, LineNumber = i })
                      .Where( x => x.Line.Contains("pattern"))
                      .ToList();

foreach (var line in targetLines)
{
    Console.WriteLine("{0} : {1}", line.LineNumber, line.Line);
}

Since the console output is a side effect it should be separate from the LINQ query itself.

Upvotes: 10

vlad
vlad

Reputation: 4778

something like this should work

var result = from line in File.ReadAllLines(@"path")
             where line.Substring(0,1) == "a" // put your criteria here
             select line

Upvotes: -1

Related Questions