Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
user705414 Avatar asked May 05 '11 14:05

user705414


People also ask

How do I convert a dictionary to a string?

You can easily convert a Python dictionary to a string using the str() function. The str() function takes an object (since everything in Python is an object) as an input parameter and returns a string variant of that object.

Can dictionary be serialized in C#?

The serialization and deserialization of . NET objects is made easy by using the various serializer classes that it provides. But serialization of a Dictionary object is not that easy. For this, you have to create a special Dictionary class which is able to serialize itself.


1 Answers

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] */ 
like image 132
alextercete Avatar answered Oct 05 '22 23:10

alextercete