Wednesday, June 11, 2008 10:07 AM royashbrook

count lines with linq

so i needed to count the lines of a bunch of different filetypes in a folder. i decided to try using linq for this. here's what i came up with. basically a single linq statement =P

you can tune the regex to taste. i just said (i think, i'm not a regex wizard) something that isn't a newline (.+) and the line terminators i'm using (\r\n).

 

using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace LineCounter
{
    class LineCounter
    {
        static void Main(string[] args)
        {
            // dir to search
            string d = @"c:\pathtocode";

            // regex match for newlines
            string lf = @".+\r\n";
           
            // get the file list with directory
            string[] f = Directory.GetFiles(d, "*.*", SearchOption.AllDirectories);

            // filter to only get these files
            string filter = ".cs,.resx,.sql,.htm,.html,.xml,.xsl,.xslt";

            // count total lines
            int lines = (
                    from name in f
                    where filter.Contains(Path.GetExtension(name.ToLower()))
                    select new
                    {
                        length = Regex.Matches(
                            new StreamReader(name).ReadToEnd(), lf).Count
                    }
                ).Sum(a => a.length);

            // write out the total lines
            Console.WriteLine(lines);

            Console.ReadLine();
        }
    }
}
 

Filed under: ,

Comments

No Comments