Search specific string and return whole line

Viewed 36873

What I would like to do is find all instances of a string in a text file, then add the full lines containing the said string to an array.

For example:

eng    GB    English
lir    LR    Liberian Creole English
mao    NZ    Maori

Searching eng, for example, must add the first two lines to the array, including of course the many more instances of 'eng' in the file.

How can this be done, using a text file input and C#?

4 Answers

The File object contains a static ReadLines method that returns line-by-line, in contrast with ReadAllLines which returns an array and thus needs to load the complete file in memory.

So, by using File.ReadLines and LINQ an efficient and short solution could be written as:

var found = File.ReadLines().Where(line => line.Contains("eng")).ToArray();

As for the original question, it could be optimized further by replacing line.Contains with line.StartsWith, as it seems the required term appears in the beginning of each line.

Related