mrchooo
mrchooo

Reputation: 85

converting a dictionary of dictionary to string

i have a dictionary of dictionaries:

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

i'm trying to output its contents by overriding the to string method but i cant figure out how to convert it to string.

i tried:

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

this did not work

Upvotes: 0

Views: 2562

Answers (3)

jdphenix
jdphenix

Reputation: 15415

Consider using Newtonsoft.Json, which supports serializing dictionaries to string.

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));

Output:

{"test":{"a":"apple","b":"banana","c":"cat"},"lights":{"c":"compact fluorescent","l":"light emitting diode","i":"incandescent"}}

Upvotes: 2

Stefan
Stefan

Reputation: 17648

Try this one:

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(",");

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Your version tries printing s.Keys and s.Values, which are both collections. You can print them using a loop, but you could use string.Join twice instead:

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)))
        )
    );
}

Note 1: the above syntax uses string.Format, rather than string interpolation, in both calls. If you are using a newer version of C#, you could rewrite it for a somewhat shorter code, for example

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

Note 2: For older versions of .NET add ToArray() after both selects:

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()
));

Upvotes: 3

Related Questions