Keavon
Keavon

Reputation: 7493

Get total number of non-blank lines from text file?

I am using...

File.ReadLines(@"file.txt").Count();

...to find the total number of lines in the file. How can I do this, but ignore all blank lines?

Upvotes: 10

Views: 3318

Answers (1)

Selman Genç
Selman Genç

Reputation: 101681

You can use String.IsNullOrWhiteSpace method with Count:

File.ReadLines(@"file.txt").Count(line => !string.IsNullOrWhiteSpace(line));

Or another way with All and char.IsWhiteSpace:

File.ReadLines(@"file.txt").Count(line => !line.All(char.IsWhiteSpace));

Upvotes: 16

Related Questions