Is there anyway to handy convert a dictionary to String?

后端 未结 12 1196
死守一世寂寞
死守一世寂寞 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-13 23:55

    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;
    }
    
    0 讨论(0)
  • 2020-12-13 23:55

    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.

    0 讨论(0)
  • 2020-12-13 23:57

    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();
    }
    
    0 讨论(0)
  • 2020-12-13 23:57

    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: ");
    
    0 讨论(0)
  • 2020-12-14 00:00

    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()) + "}";
    }
    
    0 讨论(0)
  • 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],...
    
    0 讨论(0)
提交回复
热议问题