views:

179

answers:

2

Hello.

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.

+3  A: 

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.

Matt Hamilton
This is how I would do it, too!
Cerebrus
This requires that all paths are absolute. Which is a good requirement since one never knows where the relative paths have been to.
Pasi Savolainen
Yeah, that's true - you may need to call Path.GetFullPath on each string and provide it with the "root" path that you know they all map to.
Matt Hamilton
That works, but it would jumble the results if there is more than one root directory in the list.
hmemcpy
A: 

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

hmemcpy