Thursday, May 5, 2011

Sorting a list with paths by deepest directory

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.

From stackoverflow
  • 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.

    Cerebrus : This is how I would do it, too!
    Pasi Savolainen : This requires that all paths are absolute. Which is a good requirement since one never knows where the relative paths have been to.
    Matt Hamilton : 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.
    hmemcpy : That works, but it would jumble the results if there is more than one root directory in the list.
  • 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

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.