Question

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 ...))
Was it helpful?

Solution

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:

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)

OTHER TIPS

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

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

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top