Search code examples
c#sortingdirectorygetfilessystem.io.file

How to custom sort the return values of Directory.GetFiles()


I am loading a list of files placed in a directory in a string array. I am using System.IO.Directory.GetFiles(),

String[] path = Directory.GetFiles(batchElements[j].DocIdPath, "*.csv", SearchOption.AllDirectories);

I'm assuming the default sort order of the returned values is by name. So my files are loaded in the following order.

  • 2713_CFPB Settlement Cost Booklet_2713_1.csv
  • 2713_CFPB Settlement Cost Booklet_2713_10.csv
  • 2713_CFPB Settlement Cost Booklet_2713_11.csv
  • 2713_CFPB Settlement Cost Booklet_2713_2.csv
  • 2713_CFPB Settlement Cost Booklet_2713_3.csv
  • 2713_CFPB Settlement Cost Booklet_2713_4.csv
  • 2713_CFPB Settlement Cost Booklet_2713_5.csv
  • 2713_CFPB Settlement Cost Booklet_2713_6.csv
  • 2713_CFPB Settlement Cost Booklet_2713_7.csv
  • 2713_CFPB Settlement Cost Booklet_2713_8.csv
  • 2713_CFPB Settlement Cost Booklet_2713_9.csv

But instead i want to collect the values in this order.

  • 2713_CFPB Settlement Cost Booklet_2713_1.csv
  • 2713_CFPB Settlement Cost Booklet_2713_2.csv
  • 2713_CFPB Settlement Cost Booklet_2713_3.csv
  • 2713_CFPB Settlement Cost Booklet_2713_4.csv
  • 2713_CFPB Settlement Cost Booklet_2713_5.csv
  • 2713_CFPB Settlement Cost Booklet_2713_6.csv
  • 2713_CFPB Settlement Cost Booklet_2713_7.csv
  • 2713_CFPB Settlement Cost Booklet_2713_8.csv
  • 2713_CFPB Settlement Cost Booklet_2713_9.csv
  • 2713_CFPB Settlement Cost Booklet_2713_10.csv
  • 2713_CFPB Settlement Cost Booklet_2713_11.csv

Appreciate help.


Solution

  • You can do:

    • Get File name only using Path.GetFileNameWithoutExtension
    • Split them based on _
    • Get Last item
    • Parse it using int.Parse or int.TryParse
    • Use that value in OrderBy with LINQ

    Code:

    var output = path.OrderBy(p => 
                            int.TryParse(Path.GetFileNameWithoutExtension(p).Split('_').Last(), out temp) ?
                            temp : int.MaxValue);
    

    If you need an array or List<T> as output then append ToArray() or ToList() to the query.