Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# map to C# Dictionary

Tags:

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?

like image 659
Dutts Avatar asked Nov 24 '14 16:11

Dutts


1 Answers

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.

like image 89
Vandroiy Avatar answered Oct 15 '22 00:10

Vandroiy