Is there anyway to handy convert a dictionary to String?

后端 未结 12 1195
死守一世寂寞
死守一世寂寞 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条回答
  •  时光说笑
    2020-12-14 00:03

    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],...
    

提交回复
热议问题