简体   繁体   中英

How do I sort files and folders by date in my asp:Gridview?

I have an application that on load displays a list of files, and date modified on my server in alphabetical order according to the file name

DirectoryInfo di = new DirectoryInfo(Server.MapPath(strDirectory));
List<FileInfo> files = di.GetFiles().ToList();

How can I sort this by date modified?

Use FileSystemInfo.LastWriteTime

List<FileInfo> files = di.EnumerateFiles()
            .OrderBy(f => f.LastWriteTime)
            .ToList();

Here is another option: (do it all at once)

List<FileInfo> files = new DirectoryInfo(Server.MapPath(strDirectory)).GetFiles()
                    .OrderByDescending(f => f.LastWriteTime)
                    .Select(f => f.Name)
                    .ToList();

Tips: you can type a dot after each extension method to explore more options for future references. (ie instead of OrderByDescending(), you can use OrderBy(); you can just do a .ToList() after ordering without doing .Select(f => f.Name) if you like)

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