我试图找出一种使用F#在特定根目录中获取最新n个文件夹的方法。以下代码是该旅程的结果,我想在此发布并分享代码示例,以帮助其他工程师尝试解决类似的问题。
open System
open System.IO
// only get the N latest FOLDERS in a directory
let getLatestNFolders (rootDirectory:string) (howmany:int) =
let latestFolders =
Directory.GetDirectories(rootDirectory)
|> Seq.cache
|> Seq.map(fun filePath -> (filePath, Directory.GetCreationTime(filePath)))
|> Seq.sortBy(fun (path, time) -> -time.Ticks) // descending order
|> Seq.take(howmany)
|> Seq.map(fun (path, time) -> path)
|> Set.ofSeq
latestFolders
let results = getLatestNFolders "c:\\temp" 3
results |> Seq.iter(fun path -> printfn "%s\n" path)
答案 0 :(得分:3)
以下是一些改进,主要集中在删除一些瑕疵:
// only get the N latest FOLDERS in a directory
let getLatestNFolders (rootDirectory:string) howmany =
Directory.GetDirectories(rootDirectory)
|> Seq.sortBy(fun path -> -Directory.GetCreationTime(path).Ticks) // descending order
|> Seq.take howmany