Reading Text Files Using LINQ

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

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

I know that I can go through the array and find each line containing the pattern and display the line number and line.

My question is:

Is it possible to do the same with LINQ?

+4
source share
3 answers

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.

+9
source

Using LINQ is possible. However, since you need a line number, the code will most likely be more readable, 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]); } } 
0
source

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 
-1
source

Source: https://habr.com/ru/post/1347002/


All Articles