0

I have a file that contains many lines, I am using a streamreader to read the file. What I need to do is count how many lines there are in this file, but at certain points the file contains a line of text as such: "-----". SO what I need to do is count the number of lines in the file excluding the lines that contains "-----".

I do not want to use the streamreader like this:

StreamReader reader = new StreamReader();
var x = reader.ReadLine()

and check if x contains "-----" and if it does increment a counter, as this is very intensive as the file would be a huge file.

Any help is much appreciated.

Thanks in advance.

johnnie
  • 1,837
  • 5
  • 23
  • 36

2 Answers2

1

Try

File.ReadLines("path").Count (l => !l.Contains("-----"));

ReadLines returns IEnumerable. Due to Linq's lazy evaluation the whole file won't be read into memory in order to count the number of lines.

Using

File.ReadAllLines(...) 

which is what I mistakenly used in my answer originally would read the whole file into memory.

Phil
  • 42,255
  • 9
  • 100
  • 100
1

I would use:

var count = File.ReadLines("foo.txt")
                .Count(line => !line.Contains("-----"));

Note that File.ReadLines reads in a streaming fashion, so this will only actually read one at a time.

However, that effectively will do what you've described yourself not wanting to do... just in a rather prettier way. You say it's "very intensive" - but this in inherent work. If you're trying to count the number of lines containing a certain pattern, you've clearly got to read each line. I don't see how you think that's avoidable.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194