136

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?

Dariusz Woźniak
  • 9,640
  • 6
  • 60
  • 73
user705414
  • 20,472
  • 39
  • 112
  • 155

12 Answers12

211

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]
*/
alextercete
  • 4,871
  • 3
  • 22
  • 36
154

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()) + "}";
}
James McMahon
  • 48,506
  • 64
  • 207
  • 283
Tim Rogers
  • 21,297
  • 6
  • 52
  • 68
13

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}
Ani
  • 111,048
  • 26
  • 262
  • 307
9

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.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
8

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();
}
JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169
4

I got this simple answer.. Use JavaScriptSerializer Class for this.

And you can simply call Serialize method with Dictionary object as argument.

Example:

var dct = new Dictionary<string,string>();
var js = new JavaScriptSerializer();
dct.Add("sam","shekhar");
dct.Add("sam1","shekhar");
dct.Add("sam3","shekhar");
dct.Add("sam4","shekhar");
Console.WriteLine(js.Serialize(dct));

Output:

{"sam":"shekhar","sam1":"shekhar","sam3":"shekhar","sam4":"shekhar"}
Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79
3

Another solution:

var dic = new Dictionary<string, double>()
{
    {"A", 100.0 },
    {"B", 200.0 },
    {"C", 50.0 }
};

string text = dic.Select(kvp => kvp.ToString()).Aggregate((a, b) => a + ", " + b);

Value of text: [A, 100], [B, 200], [C, 50]

Are
  • 197
  • 1
  • 5
3

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],...
seairth
  • 1,966
  • 15
  • 22
0

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.

eeldivad
  • 43
  • 6
0

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: ");
Blaato
  • 129
  • 10
0

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;
}
Syjin
  • 2,740
  • 1
  • 27
  • 31
-5

What you have to do, is to create a class extending Dictionary and overwrite the ToString() method.

See you

Amedio
  • 895
  • 6
  • 13
  • May I know Why someone pointed -1 to this? :) thanks, If I'm wrong I would like where I'm wrong. Thank you. – Amedio May 05 '11 at 14:26
  • 4
    I didn't downvote this answer, but it doesn't provide sample code. Also, subclassing seems like an unnecessary hammer when you can just write an extension method as shown in some of the other answers; this also allows you to call the extension method directly on dictionaries you're getting from code outside your control where you wouldn't be able to just use your subclass. – Eliot Apr 22 '16 at 00:52