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

时间:2022-02-02 13:09:11

How do I "convert" a Dictionary into a sequence so that I can sort by 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 个解决方案

#1


A System.Collections.Dictionary<K,V> is an IEnumerable<KeyValuePair<K,V>>, and the F# Active Pattern 'KeyValue' is useful for breaking up KeyValuePair objects, so:

System.Collections.Dictionary 是IEnumerable >,F#Active Pattern'KeyValue'对于分解KeyValuePair对象很有用,因此: ,v>

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)

#2


You may also find the dict function useful. Let F# do some type inference for you:

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

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

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

#3


Another option, which doesn't need a lambda until the end

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

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

with help from https://gist.github.com/theburningmonk/3363893

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

#1


A System.Collections.Dictionary<K,V> is an IEnumerable<KeyValuePair<K,V>>, and the F# Active Pattern 'KeyValue' is useful for breaking up KeyValuePair objects, so:

System.Collections.Dictionary 是IEnumerable >,F#Active Pattern'KeyValue'对于分解KeyValuePair对象很有用,因此: ,v>

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)

#2


You may also find the dict function useful. Let F# do some type inference for you:

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

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

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

#3


Another option, which doesn't need a lambda until the end

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

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

with help from https://gist.github.com/theburningmonk/3363893

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