F#中的Dictionary有一個構造函數(將Seq/List作爲輸入並輸出字典)?我寫了下面的代碼,我想要做什麼,但我只是好奇,也許它已經實現(所以我並不需要實現它自己)來自List/Seq的F#字典生成器
let DictionaryBuilder (keyFunc:'a->'b) (valueFunc:'a->'c) aList =
let dict = new Dictionary<'b,'c>()
aList
|> Seq.iter (fun a -> dict.Add(keyFunc a, valueFunc a))
dict // return
我知道,在C#中,可以使用.ToDictionary(使用System.Linq)
// using System.Collections.Generic;
// using System.Linq;
List<string> example = new List<string> {"a","b","c"};
Dictionary<string,string> output = example.ToDictionary(x => x+"Key", x => x+"Value");
// Output: {"aKey": "aValue", "bKey": "bValue", "cKey": "cValue"}
非常感謝。
注意'dict'生成一個只讀字典(當您嘗試添加或刪除項目時會引發異常)。你可以通過再次將該字典傳遞給Dictionary構造函數來解決這個問題:'... |> dict |> System.Collections.Generic.Dictionary' – TheQuickBrownFox
好的聲明,謝謝 –