Sort the list using paths to the deepest directory

I need to sort a list containing 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 the class Paththat I can use for this?

Thanks! J.

+3
source share
2 answers

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

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

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

+6
source

, , ?

var paths = new List<string>
{
  "\\New Folder",
  "\\New Folder\\tools",
  "\\Windows",
  "\\Windows\\System32",
  "\\New Folder\\tools\\1",
};

var result = paths.OrderByDescending(s => s);

, string[], :

Array.Sort(paths);
Array.Reverse(paths);

:

\ Windows\System32
\ Windows
\ \tools\1
\ \
\

+2

Source: https://habr.com/ru/post/1707654/


All Articles