F# collection initializer syntax

后端 未结 6 574
猫巷女王i
猫巷女王i 2021-02-03 19:05

What is the collection initializer syntax in F#? In C# you can write something like:

new Dictionary() {
    {\"One\", 1},
    {\"two\", 2}}
         


        
6条回答
  •  长发绾君心
    2021-02-03 19:34

    I don't believe F# has an explicit collection initializer syntax. However it's usually very easy to initialize F# collections. For example

    let map = [ ("One", 1); ("Two", 2) ] |> Map.ofSeq
    

    Getting to BCL collections is usually a bit more difficult because they don't always have the handy conversion functions. Dictionary works though because you can use the LINQ method

    let map = 
      let list = [ ("One", 1); ("Two", 2) ] 
      System.Linq.Enumerable.ToDictionary(list, fst, snd)
    

提交回复
热议问题