简体   繁体   中英

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. 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. 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. Changing OrderBy to OrderByDescending reverses the results as expected.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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