Chris-AZ
Chris-AZ

Reputation: 31

count rows in a text file

I have the following rows in a text file and I need to know how many rows end with a Y and how many end with a N.

there is a space after the Y and after the N.

The faster the better as it might contain a million or so rows.(so I would prefer not to loop through every line)

Upvotes: 0

Views: 279

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500085

Well you're going to have to loop through every line, certainly. There's really no getting around that. You could then use LINQ to count them reasonably easily:

var query = File.ReadLines("file.txt")
                .Select(line => new { Y = line.EndsWith("Y ") ? 1 : 0,
                                      N = line.EndsWith("N ") ? 1 : 0 })
                .Aggregate(new { Y = 0, N = 0 },
                           (current, next) => new { Y = current.Y + next.Y,
                                                    N = current.N + next.N });

var yCount = query.Y;
var nCount = query.N;

If there isn't exactly one space after the Y / N, change it to use Trim() instead... for example:

var query = File.ReadLines("file.txt")
                .Select(line => line.Trim())
                .Select(line => new { Y = line.EndsWith("Y") ? 1 : 0,
                                      N = line.EndsWith("N") ? 1 : 0 })
// remainder of code as before

This will iterate through the whole file just once, counting as it goes. Admittedly it's creating a lot of objects, but the GC is pretty good. It doesn't pull the whole file into memory, or read it twice.

Upvotes: 7

Related Questions