The source code to count the files based on extension using LINQ in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//Program to count the files based on
//extension using LINQ in C#.
using System;
using System.IO;
using System.Linq;
class LinqDemo
{
public static void Main()
{
string[] fileNames = {"file1.txt","file2.pdf","file3.xml","file4.txt","file5.pdf"};
var result = fileNames.Select(file => Path.GetExtension(file).TrimStart('.').ToLower())
.GroupBy(x => x, (ext, extCnt) => new
{
Extension = ext,
Count = extCnt.Count()
});
foreach (var val in result)
{
Console.WriteLine(val.Count+"File(s) with "+val.Extension+" Extension ");
}
}
}
Output:
2File(s) with pdf Extension
1File(s) with xml Extension
Press any key to continue . . .
Explanation:
In the above program, we created a class LinqDemo that contains the Main() method. In the Main() method we created a string array fileNames that contains the name of the files with different extensions. Then we count the file extensions and group them using LINQ. Then we print the extension and its count using the foreach loop on the console screen.
Program:
The source code to count the files based on extension using LINQ in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class LinqDemo that contains the Main() method. In the Main() method we created a string array fileNames that contains the name of the files with different extensions. Then we count the file extensions and group them using LINQ. Then we print the extension and its count using the foreach loop on the console screen.