views:

191

answers:

2

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 ...))
+6  A: 

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)
Brian
Oh right KeyValue!Thanks Brian!
+5  A: 

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>
DannyAsher