如何将词典“转换”为序列,以便按键值排序?
let results = new Dictionary() results.Add("George", 10) results.Add("Peter", 5) results.Add("Jimmy", 9) results.Add("John", 2) let ranking = results ??????? |> Seq.Sort ?????? |> Seq.iter (fun x -> (... some function ...))
答案 0 :(得分:22)
System.Collections.Dictionary< K,V>是IEnumerable< KeyValuePair< K,V>>,F#Active Pattern'KeyValue'对于分解KeyValuePair对象很有用,所以:
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)
答案 1 :(得分:13)
您可能还会发现dict
功能很有用。让F#为你做一些类型推断:
let results = dict ["George", 10; "Peter", 5; "Jimmy", 9; "John", 2]
> val results : System.Collections.Generic.IDictionary<string,int>
答案 2 :(得分:2)