Search code examples
c#linqienumerablefile-extension

C# LINQ Queries - Get File Extension Type using IEnumerable<string>


I currently have a method that recursively enumerates all the files on my desktop and returns them as an IEnumerable<string>. What I am trying to now do is create a method that takes that IEnumerable<string> as the parameter and uses LINQ to group/order them by their file type. I am having trouble getting the file types. After experimenting, I have gotten this:

foreach(string file in files){
                FileInfo f = new FileInfo(file);
                Console.WriteLine(f.Extension);
                
}

I am able to get the extensions of all files, but cannot figure out how to get that information using a LINQ query


Solution

  • You can use the GroupBy method:

    var files = new[] { "c://file1.txt", "c://file2.png", "c://file3.txt" };
    var groups = files.Select(f => new FileInfo(f)).GroupBy(file => file.Extension, file => file, 
        (key, g) => new
    {
        Extension = key, Files = g.OrderBy(f => f.Name).ToList()
    });
    foreach (var fileGroup in groups)
    {
        var ext = fileGroup.Extension;
        var innerFiles = fileGroup.Files;
        Console.WriteLine($@"Files with extension {ext}: {innerFiles.Count} files");
    }