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
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: