Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Text Files with LINQ

Tags:

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?

like image 382
coson Avatar asked Jan 21 '23 01:01

coson


1 Answers

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.

like image 143
BrokenGlass Avatar answered Feb 01 '23 21:02

BrokenGlass