ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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

Here, we are going to learn how to count the files based on extension using LINQ in C#?
Submitted by Nidhi, on August 20, 2020

Here will write a program to count files with different extensions using LINQ in C#. Suppose we have two files with ".txt" and 2 files with ".pdf". Here contains the name of the file in a string array, and then find the count of file with specific extension using LINQ.

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.

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.