首页 > 解决方案 > 将字典(从 C# 传递)转换为 F# 中的字符串

问题描述

编辑:它已解决。答案是:

|> Seq.sortBy (fun (KeyValue(k,v)) -> k)
|> Seq.map (fun (KeyValue(k,v)) -> (sprintf "%s:%s" k v))
|> String.concat ","

原始问题:

我正在尝试做这个的 F# 版本:

var postData = "{"
   + string.Join(
       ",",
       sortedParameters.Select(item => $"\"{item.Key}\":\"{item.Value}\"").ToList())
   + "}";

我有以下字典,来自 C#:

{
    { "a", "1" },
    { "c", "3" },
    { "b", "2" },
}

我想对其进行排序,然后输出字符串中的所有值,如下所示:

"a":"1", "b":"2", "c":"3"

所以,我是这样开始的:

let Test (values : Dictionary<string, string>) : string =
    |> Seq.sortBy (fun (KeyValue(k,v)) -> k)
    |> Seq.iter (fun (KeyValue(k,v)) -> (sprintf "%s:%s" k v))

但最后一部分没有编译:

Compilation error (line 13, col 50): Type mismatch. Expecting a string -> string -> unit but given a string -> string -> string The type 'unit' does not match the type 'string'
Compilation error (line 13, col 60): This expression was expected to have type string but here has type int

我不明白错误信息。我的假设是这会返回一个字符串列表,例如:

{
    "a:1", "b:2", "c:3"
}

我必须在下一步中加入一个字符串

显然,它不是那样做的:)

我错过了什么?

标签: f#

解决方案


推荐阅读