4

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

让结果 = 新字典()

results.Add("乔治", 10)
results.Add("彼得", 5)
结果。添加(“吉米”,9)
结果。添加(“约翰”,2)

让排名=
  结果
  ??????
  |> 序列排序 ??????
  |> Seq.iter (fun x -> (... some function ...))
4

3 回答 3

22

System.Collections.Dictionary<K,V> 是 IEnumerable<KeyValuePair<K,V>>,F# 活动模式“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)
于 2009-07-13T00:37:14.203 回答
13

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

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

> val results : System.Collections.Generic.IDictionary<string,int>
于 2009-07-13T10:36:39.440 回答
3

另一种选择,直到最后都不需要 lambda

dict ["George", 10; "Peter", 5; "Jimmy", 9; "John", 2]
|> Seq.map (|KeyValue|)
|> Seq.sortBy fst
|> Seq.iter (fun (k,v) -> ())

在https://gist.github.com/theburningmonk/3363893的帮助下

于 2016-09-08T13:48:11.393 回答