Is there anyway to handy convert a dictionary to String?

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?


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]
*/

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

How about an extension-method such as:

public static string MyToString<TKey,TValue>
      (this IDictionary<TKey,TValue> dictionary)
{
    if (dictionary == null)
        throw new ArgumentNullException("dictionary");

    var items = from kvp in dictionary
                select kvp.Key + "=" + kvp.Value;

    return "{" + string.Join(",", items) + "}";
}

Example:

var dict = new Dictionary<int, string>
{
    {4, "a"},
    {5, "b"}
};

Console.WriteLine(dict.MyToString());

Output:

{4=a,5=b}

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

Maybe:

string.Join
(
    ",",
    someDictionary.Select(pair => string.Format("{0}={1}", pair.Key.ToString(), pair.Value.ToString())).ToArray()
);

First you iterate each key-value pair and format it as you'd like to see as string, and later convert to array and join into a single string.