Well yes - with the help of Select() overload, which takes an index, we can do this by projecting an anonymous type containing a string, 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 console output is a side effect, it should be separated from the LINQ query itself.
source share