Is there anyway to handy convert a dictionary to String?

后端 未结 12 1255
死守一世寂寞
死守一世寂寞 2020-12-13 23:50

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?

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 00:06

    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 implements IEnumerable>.

    Example

    Console.WriteLine(string.Join(Environment.NewLine, new Dictionary {
        {"key1", "value1"},
        {"key2", "value2"},
        {"key3", "value3"},
    }));
    /*
    [key1, value1]
    [key2, value2]
    [key3, value3]
    */
    

提交回复
热议问题