简体   繁体   中英

Sort DirectoryInfo by creation date

This code gives me the a list of folders. Without sorting it comes up oldest first. Although I don't think that could be guaranteed.(it could sort based on file name which is a date). I want to use the OrderBy or OrderByDescending function to sort it newest first based on the creation date.

Dim di As New DirectoryInfo(root)
folderList = di.GetDirectories()

'does not work
folderList.OrderByDescending(Function(x) x.CreationTime)

Thank you

You need to (re)assign the value that OrderByDescending returns to the variable, it will not order the original collection.

For example:

folderList = folderList.
    OrderByDescending(Function(x) x.CreationTime).
    ToArray()

Another option is to sort the original array:

Array.Sort(folderList, Function(d1, d2) d1.CreationTime.CompareTo(d2.CreationTime))

I'm using this overload of Array.Sort with a Comparison(Of T) .

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