如何使用F#获取最新的x目录文件夹条目

时间:2016-01-19 00:14:31

标签: .net search f#

我试图找出一种使用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)

1 个答案:

答案 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