What is the collection initializer syntax in F#? In C# you can write something like:
new Dictionary() {
{\"One\", 1},
{\"two\", 2}}
>
As Jared says, there is no built-in support for this for arbitrary collections. However, the C# code is just syntactic sugar for Add
method calls, so you could translate it to:
let coll = MyCollectionType()
["One", 1; "Two", 2] |> Seq.iter coll.Add
If you want to get fancy, you could create an inline
definition to streamline this even further:
let inline initCollection s =
let coll = new ^t()
Seq.iter (fun (k,v) -> (^t : (member Add : 'a * 'b -> unit) coll, k, v)) s
coll
let d:System.Collections.Generic.Dictionary<_,_> = initCollection ["One",1; "Two",2]