Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ on Directory.GetFiles with filtering and sorting with multiple sort criteria

The following works fine for getting a list of *.png and *.jpg files from a specified directory, sorted by a file name.

DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Images/"));

List<string> fileNames = di.GetFiles("*.*")
 .Where(f => f.Name.EndsWith(".png") || f.Name.EndsWith(".jpg"))
 .OrderBy(f => f.Name).Select(f => f.Name).ToList();

I wanted to enhance the above by making sorting work first with a file extension and then by a file name, hence:

DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Images/"));

List<string> fileNames = di.GetFiles("*.*")
  .Where(f => f.Name.EndsWith(".png") || f.Name.EndsWith(".jpg"))
  .OrderBy(f => new {f.Extension, f.Name}).Select(f => f.Name).ToList();

This flags a runtime error: At least one object must implement IComparable and suspect the OrderBy new {f.Extension, f.Name} may be incorrect??

How can I fix this?

like image 250
user2921851 Avatar asked Mar 14 '23 18:03

user2921851


1 Answers

In order to specify multiple orderings you can use the ThenBy method after the initial OrderBy call:

List<string> fileNames = di.GetFiles("*.*")
  .Where(f => f.Name.EndsWith(".png") || f.Name.EndsWith(".jpg"))
  .OrderBy(f => f.Extension)
  .ThenBy(f => f.Name)
  .Select(f => f.Name)
  .ToList();
like image 71
Jared Russell Avatar answered Mar 16 '23 08:03

Jared Russell