Q:

C# program to count the files based on extension using LINQ

belongs to collection: C# LINQ Programs

0

C# program to count the files based on extension using LINQ

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

//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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# LINQ Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to generate random even numbers using L... >>