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",
"", "abc.PDF", "abc.xml", "zy.txt" };

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

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.



Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


0 Responses to "Count File Extensions and Group it using LINQ"

Copyright © 2009-2015 All Rights Reserved for by Suprotim Agarwal | Terms and Conditions