F# 映射到 C# 字典 [英] F# map to C# Dictionary
问题描述
我正在尝试将 F# 映射转换为 C# 字典,到目前为止我正在使用:
I'm trying to convert an F# map to a C# dictionary, so far I am using:
let toDictionary (map : Map<_, _>) : Dictionary<_, _> =
let dict = new Dictionary<_, _>()
map |> Map.iter (fun k v -> dict.Add(k, v))
dict
只是感觉有点笨拙,我对 F# 很陌生,所以有更好的方法吗?
It just feels a little clunky, I'm quite new to F# so it there a better way?
推荐答案
1.如果你想要标准的 Dictionary 实现: 查看 jbtule 的答案
2.如果你想要一个不可变的、快速的 IDictionary: dict 函数 来自当前的 F# 核心库允许从任何键值元组序列创建只读字典:
2. If you want an immutable, fast IDictionary: the dict function from the current F# core library allows to create a read-only dictionary from any sequence of key-value tuples:
myDict |> Map.toSeq |> dict
返回值的类型为 IDictionary
,因此应该可以从 C# 中使用.感谢 Daniel 的回答让我想起 Map.toSeq.
The return value has type IDictionary
and should thus be usable from C#. Thanks to Daniel's answer for reminding me of Map.toSeq.
3.如果您可以直接使用 Map:Map<,> 实现了 IDictionary,从 C# 使用它应该很方便.但是,map的访问是O(log n),而基于hash的字典访问是常量顺序.
3. If you're fine with using Map directly: Map<,> implements IDictionary, which should be convenient to use from C#. However, access of a map is O(log n), while hash-based dictionary access is constant order.
这篇关于F# 映射到 C# 字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!