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



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

comments

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

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions