Como "converter" um dicionário em uma sequência em f#?
-
12-09-2019 - |
Pergunta
Como faço para "converter" um dicionário em uma sequência para que eu possa classificar pelo valor da chave?
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 ...))
Solução
A System.Collection.Dictionaryu003CK,V> é um ienumerable u003CKeyValuePairu003CK,V> >, e o padrão F# Active 'KeyValue' é útil para dividir objetos KeyValuepair, então:
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)
Outras dicas
Você também pode encontrar o dict
função útil. Deixe f# fazer algum tipo de inferência por você:
let results = dict ["George", 10; "Peter", 5; "Jimmy", 9; "John", 2]
> val results : System.Collections.Generic.IDictionary<string,int>
Outra opção, que não precisa de um lambda até o fim
dict ["George", 10; "Peter", 5; "Jimmy", 9; "John", 2]
|> Seq.map (|KeyValue|)
|> Seq.sortBy fst
|> Seq.iter (fun (k,v) -> ())
com ajuda de https://gist.github.com/theburningmonk/3363893
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow