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

时间:2009-07-13 00:31:08

标签: 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 ...))

3 个答案:

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

另一个选项,在结束之前不需要lambda

{{1}}

https://gist.github.com/theburningmonk/3363893

的帮助下