给定两个词典,如何覆盖一个词典中的匹配项目与另一个词典中的项目,而其余项目保持不变

本文关键字:项目 另一个 余项目 一个 两个 何覆盖 覆盖 | 更新日期: 2023-09-27 18:36:11

这是起始代码:

Dictionary<string,object> dest=...;
IDictionary<string,object> source=...;
// Overwrite in dest all of the items that appear in source with their new values
// in source. Any new items in source that do not appear in dest should be added.
// Any existing items in dest, that are not in source should retain their current 
// values.
...

我显然可以使用遍历源代码中所有项目的 foreach 循环来做到这一点,但是在 C# 4.0(也许是 LINQ)中是否有一些速记方法可以做到这一点?

谢谢

给定两个词典,如何覆盖一个词典中的匹配项目与另一个词典中的项目,而其余项目保持不变

foreach非常

小。 为什么要把事情复杂化?

foreach(var src in source)
{
    dest[src.Key] = src.Value;
}

如果你要经常重复这个,你可以写一个扩展方法:

public static void MergeWith<TKey, TValue>(this Dictionary<TKey,TValue> dest, IDictionary<TKey, TValue> source)
{
    foreach(var src in source)
    {
        dest[src.Key] = src.Value;
    }
}
//usage:
dest.MergeWith(source);

至于"使用 LINQ"执行此操作,查询部分意味着 LINQ 方法应该没有副作用。 有副作用经常让我们这些期望没有副作用的人感到困惑。

这个

相当丑陋,但它可以完成工作:

source.All(kv => { dest[kv.Key] = kv.Value; return true; });