有没有比使用下面示例中的两个选项之一复制/添加source字典的所有内容更简单的方法destination Dictionary<T1, T2>?
Dictionary<string, int> source = new Dictionary<string, int>(),
destination = new Dictionary<string, int>();
source.Add("Developers", 1);
source.Add("just", 2);
source.Add("wanna have", 3);
source.Add("FUN!", 4);
// Option 1 (feels like a hack):
//
source.All(delegate(KeyValuePair<string, int> p)
{
destination.Add(p.Key, p.Value);
return true;
});
// Option 2:
//
foreach (string k in source.Keys)
{
destination.Add(k, source[k]);
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是类似的东西.ForEach().
是的,您可以使用构造函数:
Dictionary<string, int> destination = new Dictionary<string, int>(source);
Run Code Online (Sandbox Code Playgroud)
如果destination已经填写了,你不想丢失它们,我会使用这个:
foreach (var kv in source)
if (!destination.ContainsKey(kv.Key))
destination.Add(kv.Key, kv.Value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |