如何将字典"转换"为F#中的序列?

4 f# dictionary sequence key-value

如何将字典"转换"为序列,以便按键值排序?

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 ...))

Bri*_*ian 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)
Run Code Online (Sandbox Code Playgroud)


Dan*_*her 13

您可能还会发现该dict功能很有用.让F#为你做一些类型推断:

let results = dict ["George", 10; "Peter", 5; "Jimmy", 9; "John", 2]

> val results : System.Collections.Generic.IDictionary<string,int>
Run Code Online (Sandbox Code Playgroud)