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

问题描述 投票:0回答:3

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

让结果 = new Dictionary()

结果.Add("乔治", 10)
结果.Add("彼得", 5)
结果.Add("吉米", 9)
结果.Add("约翰", 2)

让排名=
  结果
  ??????
  |> 顺序排序 ??????
  |> Seq.iter (fun x -> (...某个函数 ...))
f# dictionary sequence key-value
3个回答
23
投票

System.Collections.Dictionary 是一个 IEnumerable>,并且 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)

13
投票

您可能还会发现

dict
功能很有用。让 F# 为您做一些类型推断:

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

> val results : System.Collections.Generic.IDictionary<string,int>

4
投票

另一个选项,直到最后都不需要 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 的帮助下

© www.soinside.com 2019 - 2024. All rights reserved.