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)
ale*_*ete 83
如果您只是想序列化以进行调试,则更短的方法是:
var asString = string.Join(Environment.NewLine, dictionary);
Run Code Online (Sandbox Code Playgroud)
这是因为String.Join
是一个IDictionary<TKey, TValue>
.
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)
没有方便的方式.你必须自己动手.
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)
也许:
string.Join
(
",",
someDictionary.Select(pair => string.Format("{0}={1}", pair.Key.ToString(), pair.Value.ToString())).ToArray()
);
Run Code Online (Sandbox Code Playgroud)
首先,您迭代每个键值对并将其格式化为您希望将其视为字符串,然后转换为数组并加入单个字符串。
归档时间: |
|
查看次数: |
59747 次 |
最近记录: |