C# sorting a list of (sub)directories with natural sorting

247 views Asked by At

I'm trying to sort a list of directories and subdirectories with natural sorting and right now it isn't entirely what I want.

Right now I'm getting this:

    D:/pictures/apples/a.txt
    D:/pictures/apples pink/c.txt
    D:/pictures/bananas/asdasd.txt
    D:/pictures/lemons/foo.txt
    D:/pictures/lemons yellow/bar.txt
    D:/pictures/lemons/fresh/c.txt
    D:/pictures/oranges/341/d.txt

What I want is this:

    D:/pictures/apples/a.txt
    D:/pictures/apples pink/c.txt
    D:/pictures/bananas/asdasd.txt
    D:/pictures/lemons/foo.txt
    D:/pictures/lemons/fresh/c.txt
    D:/pictures/lemons yellow/bar.txt
    D:/pictures/oranges/341/d.txt

Note the subdirectory of lemons should be before the other.

For natural sorting, I'm using the built-in function of Windows as described here and I'm using the following code to achieve the above:

    var files = Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
        .OrderBy(f => Path.GetDirectoryName(f), new NaturalSortComparer())
        .ThenBy(f => f.Count(c => c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar))
        .Where(file => extensions.Contains(Path.GetExtension(file.ToLower())));
0

There are 0 answers