无论如何要方便地将字典转换为字符串?

use*_*414 64 c#

我发现词典中ToString的默认实现并不是我想要的.我想要{key=value, ***}.

任何方便的方式来获得它?

Tim*_*ers 96

试试这个扩展方法:

public static string ToDebugString<TKey, TValue> (this IDictionary<TKey, TValue> dictionary)
{
    return "{" + string.Join(",", dictionary.Select(kv => kv.Key + "=" + kv.Value).ToArray()) + "}";
}
Run Code Online (Sandbox Code Playgroud)

  • @StevenJeuris:如果您使用的版本低于NET 4.0,则确实需要`ToArray()` (3认同)

ale*_*ete 83

如果您只是想序列化以进行调试,则更短的方法是:

var asString = string.Join(Environment.NewLine, dictionary);
Run Code Online (Sandbox Code Playgroud)

这是因为String.Join是一个IDictionary<TKey, TValue>.

  • 辉煌!我一生都在哪里? (4认同)
  • +1不是真的很漂亮,但它的工作原理很简单. (3认同)
  • 请注意,这需要.NET 4 (3认同)
  • 不适用于`ListDictionary`。否则很棒,点赞 (2认同)

Ani*_*Ani 10

如何扩展方法,如:

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) + "}";
}
Run Code Online (Sandbox Code Playgroud)

例:

var dict = new Dictionary<int, string>
{
    {4, "a"},
    {5, "b"}
};

Console.WriteLine(dict.MyToString());
Run Code Online (Sandbox Code Playgroud)

输出:

{4=a,5=b}
Run Code Online (Sandbox Code Playgroud)


JSB*_*ոգչ 8

没有方便的方式.你必须自己动手.

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();
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*zer 6

也许:

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

首先,您迭代每个键值对并将其格式化为您希望将其视为字符串,然后转换为数组并加入单个字符串。