Search code examples
c#linqfilenamesfile-extension

Getting filenames without extensions except for duplicates


I am populating a list with all the file names from a folder (minus those with a .blah extension). I want file names without their extension, except for the case where the directory contains two identical file names (but with obviously different extensions).

Here's an example...

Take the following files from a folder:

blah.txt
blah.doc
test.txt
ex.dox

What I want to happen in my list:

blah.txt
blah.doc
test
ex

This is what I have so far, but this is obviously just adding all the files without extensions, and not taking into consideration files with the same name:

foreach (string file in Directory.GetFiles(folderName).Where(name => !name.EndsWith(".blah")))
{
    list.Add(Path.GetFileNameWithoutExtension(file));
}

I was wondering if there would be a cool, clean way to do this.


Solution

  • This looks pretty clean:

    Directory.GetFiles(folderName)
    .Where(f => !f.EndsWith(".blah"))
    .Select (f => new FileInfo(f))
    .Select(f => new { NoExt = Path.GetFileNameWithoutExtension(f.Name),  f.Name})
    .GroupBy (f => f.NoExt)
    .SelectMany(g => g.Count() > 1 ? g.Select(f => f.Name) 
                                   : g.Select (f => f.NoExt))