Reputation:
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.
Upvotes: 3
Views: 2966
Reputation: 31548
I assume those paths are strings, so why not just sort them in descending order?
var paths = new List<string>
{
"\\New Folder",
"\\New Folder\\tools",
"\\Windows",
"\\Windows\\System32",
"\\New Folder\\tools\\1",
};
var result = paths.OrderByDescending(s => s);
Or if they are in a string[]
you can use:
Array.Sort(paths);
Array.Reverse(paths);
Result is:
\Windows\System32
\Windows
\New Folder\tools\1
\New Folder\tools
\New Folder
Upvotes: -1
Reputation: 204199
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.
Upvotes: 7