C# - Count the files based on extension using LINQ

Learn, how to count the files based on extension using LINQ in C#? By Nidhi Last updated : April 01, 2023

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.

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

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.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.