Is there anyway to handy convert a dictionary to String?
Try this extension method:
public static string ToDebugString<TKey, TValue> (this IDictionary<TKey, TValue> dictionary)
{
return "{" + string.Join(",", dictionary.Select(kv => kv.Key + "=" + kv.Value).ToArray()) + "}";
}
If you just want to serialize for debugging purposes, the shorter way is to use String.Join
:
var asString = string.Join(Environment.NewLine, dictionary);
This works because IDictionary<TKey, TValue>
implements IEnumerable<KeyValuePair<TKey, TValue>>
.
Example
Console.WriteLine(string.Join(Environment.NewLine, new Dictionary<string, string> {
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"},
}));
/*
[key1, value1]
[key2, value2]
[key3, value3]
*/