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
It just feels a little clunky, I'm quite new to F# so it there a better way?
1. If you want the standard Dictionary implementation: See the answer of jbtule
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
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. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With