문제

키 값으로 정렬 할 수 있도록 사전을 시퀀스로 "변환"하려면 어떻게해야합니까?

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 ...))
도움이 되었습니까?

해결책

System.collections.dictionaryu003CK,V> ienumerable입니다 u003CKeyValuePairu003CK,V> >, 그리고 f# 활성 패턴 'KeyValue'는 keyvaluepair 객체를 분해하는 데 유용하므로 :

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)

다른 팁

당신은 또한 찾을 수 있습니다 dict 기능이 유용합니다. F#이 유형의 추론을하자 :

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

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

끝까지 람다가 필요하지 않은 또 다른 옵션

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top