如何“转换”一个字典到F#中的序列? [英] How to "convert" a Dictionary into a sequence in F#?

查看:188
本文介绍了如何“转换”一个字典到F#中的序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Dictionary转换成序列,以便按键值进行排序?

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 ...))


推荐答案

一个System.Collections.Dictionary< K,V>是一个IEnumerable< KeyValuePair< K,V >>,并且F#活动模式'KeyValue'用于分解KeyValuePair对象,所以: p>

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)

这篇关于如何“转换”一个字典到F#中的序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆