将字典字典转换为字符串

时间:2017-10-15 23:03:26

标签: c# tostring

我有一本字典词典:

Dictionary<string, Dictionary<char, string>> myDict;

我试图通过覆盖to string方法输出其内容,但我无法弄清楚如何将其转换为字符串。

我试过了:

StringBuilder str = new StringBuilder();
foreach (Dictionary<string, Dictionary<char, string>> s in str)
{
    myDict.Append(s.Keys).Append(",").Append(s.Values);
}

这不起作用

3 个答案:

答案 0 :(得分:3)

您的版本会尝试打印s.Keyss.Values,它们都是集合。您可以使用循环打印它们,但您可以使用string.Join两次:

public override string ToString() {
    return string.Join(
        ",",
        myDict.Select(
            p => string.Format(
                "{0}:{1}",
                p.Key,
                string.Join(",", p.Value.Select(x => string.Format("{0}={1}", x.Key, x.Value)))
        )
    );
}

注1:以上语法在两次调用中都使用string.Format,而不是string interpolation。如果您使用的是较新版本的C#,则可以将其重写为更短的代码,例如

string.Join(",", p.Value.Select(x => $"{x.Key}={x.Value}"))

注2:对于旧版本的.NET,在两者选择后添加ToArray()

return string.Join(
    ",",
    myDict.Select(
        p => string.Format(
            "{0}:{1}",
            p.Key,
            string.Join(",", p.Value.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray())
    ).ToArray()
));

答案 1 :(得分:2)

考虑使用Newtonsoft.Json,它支持将字典序列化为字符串。

var values = new Dictionary<string, IDictionary<char, string>>
{
    {
        "test", new Dictionary<char, string>
        {
            ['a'] = "apple",
            ['b'] = "banana",
            ['c'] = "cat"
        }
    },
    {
        "lights", new Dictionary<char, string>
        {
            ['c'] = "compact fluorescent",
            ['l'] = "light emitting diode",
            ['i'] = "incandescent"
        }
    }
};

Console.WriteLine(JsonConvert.SerializeObject(values));

输出:

  

{“test”:{“a”:“apple”,“b”:“banana”,“c”:“cat”},“lights”:{“c”:“compact fluorescent”,“l “:”发光二极管“,”i“:”白炽灯“}}

答案 2 :(得分:0)

试试这个:

StringBuilder str = new StringBuilder();
foreach (var s in myDict)
{
    foreach (var i in s.Value)
    {
        //Key is char, Value is string
        str.Append("(")
           .Append(s.Key)
           .Append(",")
           .Append(i.Key)
           .Append(",")
           .Append(i.Value)
           .Append("),");
    }
}
//remove trailing ","
var s = str.ToString().Trim(",");