Is there anyway to handy convert a dictionary to String?

后端 未结 12 1248
死守一世寂寞
死守一世寂寞 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:15

    How about an extension-method such as:

    public static string MyToString
          (this IDictionary 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
    {
        {4, "a"},
        {5, "b"}
    };
    
    Console.WriteLine(dict.MyToString());
    

    Output:

    {4=a,5=b}
    

提交回复
热议问题