[英]How to sort in a linq query?
So I am getting some files like this: 所以我得到一些像这样的文件:
int pathLength = path.Length + 1;
var files = Directory.GetFiles ( path, "*.*", SearchOption.AllDirectories )
.Where ( s => s.EndsWith ( ".bmp", StringComparison.OrdinalIgnoreCase ) ||
s.EndsWith ( ".jpg", StringComparison.OrdinalIgnoreCase ) )
.Select ( s => s.Substring ( pathLength, s.Length - pathLength ) )
.ToList ( );
and was before sorting like this: 并且在这样排序之前:
FileComparer fileComparer = new FileComparer ( );
files.Sort ( fileComparer );
But for Sort I need to use ToList. 但是对于排序,我需要使用ToList。 I am wondering if I can just add the Sort to the Linq the same way and get rid of ToList?
我想知道是否可以以相同的方式将Sort添加到Linq并摆脱ToList?
You're looking for the OrderBy
method : 您正在寻找
OrderBy
方法 :
var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".bmp", ".jpg" };
int pathLength = path.Length + 1;
var files = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
.Where(s => extensions.Contains(Path.GetExtension(s)))
.Select(s => s.Substring(pathLength))
.OrderBy(s => s, new FileComparer());
You can replace your FileComparer
class with 您可以将
FileComparer
类替换为
.OrderBy(s => !s.Contains('\\')).ThenBy(s => s)
Since false < true
, this will sort strings that start with \\\\
before other ones. 由于
false < true
,这将对以\\\\
开头的字符串进行排序。
.OrderBy(f => f, new FileComparer())
(这假设FileComparer实现了IComparer<string>
)
There's a few things you can do to improve your code : 您可以采取一些措施来改善您的代码:
like said previously, use OrderBy for sort 如前所述,使用OrderBy进行排序
write your request as a LINQ expression rather than successive method calls : 将您的请求编写为LINQ表达式,而不是连续的方法调用:
var files = (from file in Directory.GetFiles ( path, "*.*", SearchOption.AllDirectories ) where file.EndsWith ( ".bmp", StringComparison.OrdinalIgnoreCase ) || file.EndsWith ( ".jpg", StringComparison.OrdinalIgnoreCase ) orderby new FileComparer() select file);
The code above does the same than yours but is more elegant. 上面的代码与您的代码相同,但是更优雅。
To get path, extension, file name... I strongly recommend you to use System.IO.Path helpers methods rather than perform string operations like substring or contains !! 要获取路径,扩展名,文件名...我强烈建议您使用System.IO.Path帮助器方法,而不要执行诸如子字符串或包含!!的字符串操作!
Rather than use Directory.GetFiles you could instantiate a DirectoryInfo and call the GetFiles method : this one has the advantage to return an array of FileInfo, which exposes directly properties like extension, file name... 您可以实例化DirectoryInfo并调用GetFiles方法,而不是使用Directory.GetFiles:这具有返回FileInfo数组的优点,该数组直接显示扩展名,文件名等属性。
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.