I found the default implemtation of ToString in the dictionary is not what I want. I would like to have {key=value, ***}
.
Any handy way to get it?
You can loop through the Keys of the Dictionary and print them together with the value...
public string DictToString(Dictionary<string, string> dict)
{
string toString = "";
foreach (string key in dict.Keys)
{
toString += key + "=" + dict[key];
}
return toString;
}
I like ShekHar_Pro's approach to use the serializer. Only recommendation is to use json.net to serialize rather than the builtin JavaScriptSerializer since it's slower.
No handy way. You'll have to roll your own.
public static string ToPrettyString<TKey, TValue>(this IDictionary<TKey, TValue> dict)
{
var str = new StringBuilder();
str.Append("{");
foreach (var pair in dict)
{
str.Append(String.Format(" {0}={1} ", pair.Key, pair.Value));
}
str.Append("}");
return str.ToString();
}
I really like solutions with extension method above, but they are missing one little thing for future purpose - input parametres for separators, so:
public static string ToPairString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string pairSeparator, string keyValueSeparator = "=")
{
return string.Join(pairSeparator, dictionary.Select(pair => pair.Key + keyValueSeparator + pair.Value));
}
Example of using:
string result = myDictionary.ToPairString(Environment.NewLine, " with value: ");
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 want to use Linq, you could try something like this:
String.Format("{{{0}}}", String.Join(",", test.OrderBy(_kv => _kv.Key).Zip(test, (kv, sec) => String.Join("=", kv.Key, kv.Value))));
where "test" is your dictionary. Note that the first parameter to Zip() is just a placeholder since a null cannot be passed).
If the format is not important, try
String.Join(",", test.OrderBy(kv => kv.Key));
Which will give you something like
[key,value], [key,value],...