![]() |
VOOZH | about |
Given files, now we count the files based on extension using LINQ. We are considering all types of file formats like pdf, txt, xml and going to count these files based on the extension. For that, we have to know the following methods:
Example:
Input: {myfile1.txt, myfile2.txt, myfile3.xml}
Output: 3 file ---> txt
1 file ---> xml
Input: {file12.txt, file23.xml, file45.pdf}
Output: 1 file ---> txt
1 file ---> xml
1 file ---> pdf
Approach:
- Create a list of files with different extensions.
- Read the files using .GetExtension() method. Then convert the file extensions into lower case to remove case sensitiveness. Then apply trim function before this and use groupby method to get same file extensions in to one group and then use count function to count file extensions which are already in group.
var result = files.Select(f => Path.GetExtension(f) .TrimStart('.').ToLower()) .GroupBy(y => y, (ex, excnt) => new { Extension = ex, Count = excnt.Count() });
- Display the file count and extension using file count
foreach (var i in result) { Console.WriteLine(i.Count + " File --> " + i.Extension + " format "); }
Example:
Output:
3 File --> txt format 1 File --> pdf format 2 File --> xml format