我有这个C#示例,它将从整数数组中创建一个奇数和偶数的字典:
int[] values = new int[]
{
1,
2,
3,
5,
7
};
Dictionary<int, string> dictionary =
values.ToDictionary(key => key, val => (val % 2 == 1) ? "Odd" : "Even");
// Display all keys and values.
foreach (KeyValuePair<int, string> pair in dictionary)
{
Console.WriteLine(pair);
}
输出为:
[1, Odd]
[2, Even]
[3, Odd]
[5, Odd]
[7, Odd]
我想使用ToDictionary在F#中类似地进行此操作,到目前为止:
let values = [| 1; 2; 3; 5; 7 |]
let dictionary = values.ToDictionary( ??? )
// Display all keys and values.
for d in dictionary do
printfn "%d %s" d.Key d.Value
但是,我该如何在ToDictionary内部编写逻辑呢?
最佳答案
像这样:
ToDictionary(id, fun v -> if v % 2 = 1 then "Odd" else "Even")
关于c# - 如何使ToDictionary在F#中工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31060551/