Given a list of FileInfo objects, how do I sort them by date? Specifically I want to sort them by CreationTime in descending order.
给定FileInfo对象列表,如何按日期对它们进行排序?具体来说,我想按CreationTime按降序对它们进行排序。
2 个解决方案
#1
2
The Pythonic way of doing this would be:
Pythonic这样做的方法是:
fileInfos = list(DirectoryInfo(path).GetFiles())
fileInfos.sort(key=lambda f: f.CreationTime, reverse=True)
The list sort method takes a key function that is used to get the sort key for each item.
列表排序方法采用一个键函数,用于获取每个项目的排序键。
#2
1
DirectoryInfo.GetFiles() returns an array of FileInfo objects. I created a generic list to hold the FileInfo objs, and sorted using a custom comparer.
DirectoryInfo.GetFiles()返回FileInfo对象的数组。我创建了一个通用列表来保存FileInfo objs,并使用自定义比较器进行排序。
logDir = r"C:\temp"
fileInfosArray = DirectoryInfo(logDir).GetFiles("*.log")
fileInfosList = List[FileInfo]()
fileInfosList.AddRange(fileInfosArray)
fileInfosList.Sort(FileInfoCompareCreationTimeDesc)
for fileInfo in fileInfosList:
print fileInfo.CreationTime, fileInfo.LastAccessTime, fileInfo.LastWriteTime, fileInfo.Name
# comparison delegate for FileInfo objects: sort by CreationTime Descending
def FileInfoCompareCreationTimeDesc(fileInfo1, fileInfo2):
return fileInfo2.CreationTime.CompareTo(fileInfo1.CreationTime)
#1
2
The Pythonic way of doing this would be:
Pythonic这样做的方法是:
fileInfos = list(DirectoryInfo(path).GetFiles())
fileInfos.sort(key=lambda f: f.CreationTime, reverse=True)
The list sort method takes a key function that is used to get the sort key for each item.
列表排序方法采用一个键函数,用于获取每个项目的排序键。
#2
1
DirectoryInfo.GetFiles() returns an array of FileInfo objects. I created a generic list to hold the FileInfo objs, and sorted using a custom comparer.
DirectoryInfo.GetFiles()返回FileInfo对象的数组。我创建了一个通用列表来保存FileInfo objs,并使用自定义比较器进行排序。
logDir = r"C:\temp"
fileInfosArray = DirectoryInfo(logDir).GetFiles("*.log")
fileInfosList = List[FileInfo]()
fileInfosList.AddRange(fileInfosArray)
fileInfosList.Sort(FileInfoCompareCreationTimeDesc)
for fileInfo in fileInfosList:
print fileInfo.CreationTime, fileInfo.LastAccessTime, fileInfo.LastWriteTime, fileInfo.Name
# comparison delegate for FileInfo objects: sort by CreationTime Descending
def FileInfoCompareCreationTimeDesc(fileInfo1, fileInfo2):
return fileInfo2.CreationTime.CompareTo(fileInfo1.CreationTime)