Che*_*eso 10 .net extension-methods dictionary
假设我有一个Dictionary<String,String>,我想生成一个字符串表示."石头工具"的方式是:
private static string DictionaryToString(Dictionary<String,String> hash)
{
var list = new List<String> ();
foreach (var kvp in hash)
{
list.Add(kvp.Key + ":" + kvp.Value);
}
var result = String.Join(", ", list.ToArray());
return result;
}
Run Code Online (Sandbox Code Playgroud)
有没有一种有效的方法在C#中使用现有的扩展方法来做到这一点?
我知道List上的ConvertAll()和ForEach()方法,可以用来消除foreach循环.是否有类似的方法我可以在Dictionary上使用迭代项目并完成我想要的东西?
SLa*_*aks 17
在.Net 4.0中:
String.Join(", ", hash.Select(kvp => kvp.Key + ":" + kvp.Value));
Run Code Online (Sandbox Code Playgroud)
在.Net 3.5中,您需要添加.ToArray().
干得好:
public static class DictionaryExtensions
{
public static string DictionaryToString(this Dictionary<String, String> hash)
{
return String.Join(", ", hash.Select(kvp => kvp.Key + ":" + kvp.Value));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1378 次 |
| 最近记录: |