简体   繁体   English

IEnumerable如何排序 <FileInfo> testList?

[英]How to sort IEnumerable<FileInfo> testList?

DirectoryInfo dir = new DirectoryInfo("C:\Temp");
IEnumerable<FileInfo> filesList = dir.getFiles("*.zip", SearchOption.TopDirectoryOnly);   

I tried this with something like testList.OrderBy(f=>f.Name) but it doesn't work. 我用testList.OrderBy(f=>f.Name)类的testList.OrderBy(f=>f.Name)尝试了此操作,但是它不起作用。 It gives me an error. 它给了我一个错误。

I tried ... but it doesn't work. 我试过了...但是没用。 It gives me an error 它给我一个错误

You had the right idea, using LINQ and OrderBy , and likely experienced errors in some other part of your code. 您使用LINQOrderBy有了正确的想法,并且在代码的其他部分可能遇到了错误。 One likely culprit was the unescaped backslash in the path, where @ or \\\\ was needed. 可能的罪魁祸首是路径中未转义的反斜杠,其中需要@\\\\

The following block of code runs without error in Linqpad to filter and sort .txt files in my c:\\temp folder. 下面的代码块在Linqpad中运行时没有错误,以对我的c:\\temp文件夹中的.txt文件进行过滤和排序。 Changing OrderBy to OrderByDescending reverses the results as expected. OrderBy更改为OrderByDescending会按预期反转结果。

void Main()
{
    DirectoryInfo dir = new DirectoryInfo(@"C:\Temp");
    IEnumerable<FileInfo> filesList = dir.GetFiles("*.txt", SearchOption.TopDirectoryOnly);

    // Iterate on the sorted set
    foreach(var fileInfo in filesList.OrderBy(fileInfo => fileInfo.Name))
    {
        Console.WriteLine(fileInfo.Name);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM