Menus

Tuesday, December 4, 2012

Count File Extensions and Group it using LINQ

We have this application where a service reads files generated in a folder every hour and returns a string array containing the file names. A simple report needed to be generated which showed the count of files grouped by the file extension.
Here’s how it can be done using LINQ
public static void Main()
{
    // Assuming the array with file names is returned via a service
    string[] arr = {"abc1.txt", "abc2.TXT",
    "xyz.abc.pdf", "abc.PDF", "abc.xml", "zy.txt" };

    var extGrp = arr.Select(file => Path.GetExtension(file)
                                        .TrimStart('.').ToLower())
             .GroupBy(x => x,
                      (ext, extCnt) =>
                          new
                          {
                              Extension = ext,
                              Count = extCnt.Count()
                          });
    // Print values
    foreach (var a in extGrp)
        Console.WriteLine("{0} file(s) with {1} extension ",
            a.Count, a.Extension);
    Console.ReadLine();
}

In the code above, we first use the Path.GetExtension to get the extension of the specified file and then use GroupBy to count the number of files for each extension.
OUTPUT
image

No comments:

Post a Comment