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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With