Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list with paths by deepest directory

I need to sort a list that contains paths (relative or absolute) so that the deepest path appears first, for example:

\New Folder\Item1\tools\1
\New Folder\Item1\tools
\New Folder\Item1
\New Folder
etc...

Is there an API in Path class I can use to do it?

Thanks! J.


1 Answers

This is a bit out-of-the-box, but you could always do this:

var sortedList = list.OrderByDescending(
    p => p.Count(c => c == Path.DirectorySeparatorChar
        || c == Path.AltDirectorySeparatorChar));

That is, simply order by how often the path separator character appears.

like image 173
Matt Hamilton Avatar answered Mar 09 '26 21:03

Matt Hamilton