📜  将字典添加到另一个字典 c# (1)

📅  最后修改于: 2023-12-03 15:39:16.218000             🧑  作者: Mango

将字典添加到另一个字典 C#

在 C# 中,我们可以使用 Dictionary 类型来表示一个键值对映射的集合。有时候,我们需要将一个字典中的所有键值对添加到另一个字典中。这篇文章将介绍几种实现方法。

方法一:使用 foreach 循环
Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("a", 1);
dict1.Add("b", 2);

Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("c", 3);
dict2.Add("d", 4);

foreach (KeyValuePair<string, int> entry in dict1)
{
    dict2[entry.Key] = entry.Value;
}
方法二:使用 Linq 操作
Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("a", 1);
dict1.Add("b", 2);

Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("c", 3);
dict2.Add("d", 4);

dict1.ToList().ForEach(entry => dict2[entry.Key] = entry.Value);
方法三:使用 Dictionary 的 AddRange 方法
Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("a", 1);
dict1.Add("b", 2);

Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("c", 3);
dict2.Add("d", 4);

dict2.AddRange(dict1);

值得注意的是,AddRange 方法是从 .NET Framework 4.7.2 开始提供的。如果你的应用程序使用的是早期版本的 .NET Framework,你需要使用方法一或方法二。

以上是将字典添加到另一个字典 C# 的几种方法。不同的方式各有优劣,根据具体场景选择合适的方式即可。