我正在尝试编译文件名列表(带有“stat”和“kill”文件扩展名),其中文件应根据创建日期在列表中排序。我已尝试使用LINQ OrderBy
子句,但无法指定日期。这是我目前的逻辑:
var fileList = Directory.EnumerateFiles(userPath, "*.*", SearchOption.TopDirectoryOnly).Where(s => s.EndsWith(".stat", StringComparison.InvariantCultureIgnoreCase) || s.EndsWith(".kill", StringComparison.InvariantCultureIgnoreCase));
我怎么能对它们进行排序?
答案 0 :(得分:2)
改为使用DirectoryInfo - 它返回具有CreationTime属性的FileInfo个对象的序列:
DirectoryInfo dir = new DirectoryInfo(userPath);
var fileList = dir.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly)
.Where(f => f.Extension.Equals(".stat", StringComparison.InvariantCultureIgnoreCase) ||
f.Extension.Equals(".kill", StringComparison.InvariantCultureIgnoreCase))
.OrderBy(f => f.CreationTime);
您还可以使用Extension
属性来获取文件扩展名。
答案 1 :(得分:2)
您可以在Enumerable.OrderBy
中使用File.GetCreationTime
。您也可以使用Path
类:
var fileList = Directory.EnumerateFiles(userPath, "*.*", SearchOption.TopDirectoryOnly)
.Select(p => new { Path = p, Extension = Path.GetExtension(p) })
.Where(x => x.Extension.Equals(".stat", StringComparison.InvariantCultureIgnoreCase) || x.Extension.Equals(".kill", StringComparison.InvariantCultureIgnoreCase))
.OrderBy(x => File.GetCreationTime(x.Path))
.Select(x => x.Path);