Domanda

Come faccio a "convertire" un dizionario in una sequenza in modo che io possa ordinare per valore chiave?

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 ...))
È stato utile?

Soluzione

A System.Collections.Dictionary è un IEnumerable >, e la F # modello attivo 'KeyValue' è utile per rompere oggetti KeyValuePair, così:

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)

Altri suggerimenti

È inoltre possibile trovare la funzione dict utile. Sia F # fare un certo tipo di inferenza per voi:

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

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

Un'altra opzione, che non ha bisogno di una lambda fino alla fine

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top