Is there a way to convert a dictionary to String?

I found that the standard implementation of ToString in the dictionary is not what I want. I would like to have {key=value, ***} .

Any convenient way to get it?

+56
c #
May 05 '11 at 14:15
source share
12 answers

Try using 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()) + "}"; } 
+90
May 05 '11 at 14:23
source share

If you just want to serialize for debugging purposes, a shorter way is to use String.Join :

 var asString = string.Join(";", dictionary); 

This works because IDictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>> .

+71
Jun 24 '13 at 17:21
source share

How about an extension method, for example:

 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} 
+10
May 05 '11 at 2:22 pm
source share

There is no convenient way. You will have to collapse yourself.

 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(); } 
+7
May 05 '11 at 14:23
source share

May be:

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

First, you repeat each pair of key values ​​and format it as you want to see as a string, and then convert it to an array and combine it into one string.

+4
May 05 '11 at 14:22
source share

I got this simple answer. Use the JavaScriptSerializer Class to do this.

And you can just call the Serialize method with a Dictionary object as an 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"} 
+3
May 05 '11 at 14:33
source share

If you want to use Linq, you can 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 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],... 
+3
May 05 '11 at 2:56
source share

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

The meaning of the text: [A, 100], [B, 200], [C, 50]

+1
Jun 27 '16 at 13:11
source share

You can scroll through the keys of the Dictionary and type 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; } 
0
May 05 '11 at 14:23
source share

I like the ShekHar_Pro approach for using serializer. The only recommendation is to use json.net for serialization, not the built-in JavaScriptSerializer, as it is slower.

0
Oct. 20 '14 at 21:57
source share

I really like the solutions with the extension method described above, but they don’t have one trifle for future purposes - the input parameters for the delimiters, therefore:

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

Usage example:

 string result = myDictionary.ToPairString(Environment.NewLine, " with value: "); 
0
Sep 05 '18 at 9:02
source share

What you need to do is create a class that extends the Dictionary and overwrite the ToString() method.

See you

-5
May 5 '11 at 14:23
source share



All Articles