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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: