[英]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. 对于从指定目录中获取* .png和* .jpg文件的列表(按文件名排序),以下方法可以很好地工作。
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?? 这new {f.Extension, f.Name}
运行时错误: At least one object must implement IComparable
并怀疑OrderBy new {f.Extension, f.Name}
可能不正确?
How can I fix this? 我怎样才能解决这个问题?
In order to specify multiple orderings you can use the ThenBy
method after the initial OrderBy
call: 为了指定多个排序,可以在初始OrderBy
调用之后使用ThenBy
方法:
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();
Use Below code to solve your problem 使用下面的代码来解决您的问题
List<string> fileNames = di.GetFiles("*.*")
.Where(f => f.Name.EndsWith(".png") || f.Name.EndsWith(".jpg"))
.OrderBy(f => f.Extension)
.ThenByDescending(f => f.Name)
.Select(f => f.Name).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.