如何将字典“转换”为序列,以便可以按键值排序?
让结果 = new Dictionary() 结果.Add("乔治", 10) 结果.Add("彼得", 5) 结果.Add("吉米", 9) 结果.Add("约翰", 2) 让排名= 结果 ?????? |> 顺序排序 ?????? |> Seq.iter (fun x -> (...某个函数 ...))
System.Collections.Dictionary
open System.Collections.Generic
let results = new Dictionary<string,int>()
results.Add("George", 10)
results.Add("Peter", 5)
results.Add("Jimmy", 9)
results.Add("John", 2)
results
|> Seq.sortBy (fun (KeyValue(k,v)) -> k)
|> Seq.iter (fun (KeyValue(k,v)) -> printfn "%s: %d" k v)
您可能还会发现
dict
功能很有用。让 F# 为您做一些类型推断:
let results = dict ["George", 10; "Peter", 5; "Jimmy", 9; "John", 2]
> val results : System.Collections.Generic.IDictionary<string,int>
另一个选项,直到最后都不需要 lambda
dict ["George", 10; "Peter", 5; "Jimmy", 9; "John", 2]
|> Seq.map (|KeyValue|)
|> Seq.sortBy fst
|> Seq.iter (fun (k,v) -> ())