Kai Kai - 8 months ago 58
C# Question

Sort list items [full path] by file name in C#

I have a list of type string. Each string is a full path to a file. Now I would like to sort this list by the name of the file.

When I use the Sort() method, the list would be sorted by the full path. But the path can be different.

Is there a simple way to sort the list by whats left after the last \ of each item?

Answer Source

You can use System.IO.Path.GetFileName and LINQ:

files = files.OrderBy(System.IO.Path.GetFileName).ToList();

If you want to compare in a case-insensitive manner you can pass a StringComparer:

files = files.OrderBy(System.IO.Path.GetFileName, StringComparer.InvariantCultureIgnoreCase).ToList();

Note that OrderBy (and OrderByDescending) uses a stable sort algorithm as opposed to List.Sort. That means that all elements which are equal stay in the original order.