Is there anyway to handy convert a dictionary to String?

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

    I got this simple answer.. Use JavaScriptSerializer Class for this.

    And you can simply call Serialize method with Dictionary object as argument.

    Example:

    var dct = new Dictionary<string,string>();
    var js = new JavaScriptSerializer();
    dct.Add("sam","shekhar");
    dct.Add("sam1","shekhar");
    dct.Add("sam3","shekhar");
    dct.Add("sam4","shekhar");
    Console.WriteLine(js.Serialize(dct));
    

    Output:

    {"sam":"shekhar","sam1":"shekhar","sam3":"shekhar","sam4":"shekhar"}
    
    0 讨论(0)
  • 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<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]
    */
    
    0 讨论(0)
  • 2020-12-14 00:13

    What you have to do, is to create a class extending Dictionary and overwrite the ToString() method.

    See you

    0 讨论(0)
  • 2020-12-14 00:14

    Maybe:

    string.Join
    (
        ",",
        someDictionary.Select(pair => string.Format("{0}={1}", pair.Key.ToString(), pair.Value.ToString())).ToArray()
    );
    

    First you iterate each key-value pair and format it as you'd like to see as string, and later convert to array and join into a single string.

    0 讨论(0)
  • 2020-12-14 00:15

    How about an extension-method such as:

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

    Output:

    {4=a,5=b}
    
    0 讨论(0)
  • 2020-12-14 00:15

    Another solution:

    var dic = new Dictionary<string, double>()
    {
        {"A", 100.0 },
        {"B", 200.0 },
        {"C", 50.0 }
    };
    
    string text = dic.Select(kvp => kvp.ToString()).Aggregate((a, b) => a + ", " + b);
    

    Value of text: [A, 100], [B, 200], [C, 50]

    0 讨论(0)
提交回复
热议问题