在 C# 中对 Directory.GetFiles 的结果进行排序
我有这段代码来列出目录中的所有文件。
class GetTypesProfiler
{
static List<Data> Test()
{
List<Data> dataList = new List<Data>();
string folder = @"DIRECTORY";
Console.Write("------------------------------------------\n");
var files = Directory.GetFiles(folder, "*.dll");
Stopwatch sw;
foreach (var file in files)
{
string fileName = Path.GetFileName(file);
var fileinfo = new FileInfo(file);
long fileSize = fileinfo.Length;
Console.WriteLine("{0}/{1}", fileName, fileSize);
}
return dataList;
}
static void Main()
{
...
}
}
我需要根据文件大小或字母顺序打印文件信息。如何对 Directory.GetFiles() 的结果进行排序?
I have this code to list all the files in a directory.
class GetTypesProfiler
{
static List<Data> Test()
{
List<Data> dataList = new List<Data>();
string folder = @"DIRECTORY";
Console.Write("------------------------------------------\n");
var files = Directory.GetFiles(folder, "*.dll");
Stopwatch sw;
foreach (var file in files)
{
string fileName = Path.GetFileName(file);
var fileinfo = new FileInfo(file);
long fileSize = fileinfo.Length;
Console.WriteLine("{0}/{1}", fileName, fileSize);
}
return dataList;
}
static void Main()
{
...
}
}
I need to print out the file info based on file size or alphabetical order. How can I sort the result from Directory.GetFiles()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 LINQ 非常容易。
按名称排序、
按大小排序、
Very easy with LINQ.
To sort by name,
To sort by size,
按日期排序:(返回 FileInfo 的枚举):
或者按名称排序:
按文件名排序不需要创建
FileInfo
实例,但如果您想对文件应用不同的排序方法当然,最好先准备好FileInfo
对象数组,然后按Length
或Name
OrderBy
它们财产,因此这个实现。另外,看起来您无论如何都会创建FileInfo
,因此无论哪种情况,最好拥有一个FileInfo
对象的集合。抱歉,我第一次没有得到正确的答案,应该更仔细地阅读问题和文档。
To order by date: (returns an enumerable of FileInfo):
or, to order by name:
Making
FileInfo
instances isn't necessary for ordering by file name, but if you want to apply different sorting methods on the fly it's better to have your array ofFileInfo
objects in place and then justOrderBy
them byLength
orName
property, hence this implementation. Also, it looks like you are going to createFileInfo
anyway, so it's better to have a collection ofFileInfo
objects either case.Sorry I didn't get it right the first time, should've read the question and the docs more carefully.
如果您愿意,可以在 FileInfo 对象上使用 LINQ:
You can use LINQ if you like, on a FileInfo object:
试试这个,它对我有用
try this, it works for me
如果您只需要按文件名排序并且文件标题支持升序或降序逻辑顺序,则此方法有效。我添加变量以更好地控制源和搜索模式。
This works if you only need to sort by file name and the file title supports the ascending or descending logical order.I add variables to have a bit more control of the source and search pattern.
数组排序
Array Sort