简体   繁体   中英

F# map to C# Dictionary

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.

AC# Dictionary will take an IDictionary in it's constructor. Map is an IDictionary so:

let toDictionary (map : Map<_, _>) : Dictionary<_, _> = Dictionary(map)
let toDictionary = Map.toSeq >> dict

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM