【发布时间】:2017-11-24 19:51:44
【问题描述】:
如果我实例化一个新的Dictionary,我可以传入许多值:
Dictionary<string, string> data = new Dictionary<string, string>(){
{ "Key1", "Value1" },
{ "Key2", "Value2" },
{ "Key3", "Value3" },
{ "Key4", "Value4" },
{ "Key5", "Value5" },
}
但是,如果我已经有一个Dictionary,例如当它传入参数时,我需要为每个键值对调用Add:
data.Add("Key1", "Value1");
data.Add("Key2", "Value2");
data.Add("Key3", "Value3");
data.Add("Key4", "Value4");
data.Add("Key5", "Value5");
我想知道是否有一种“速记”方法可以一次将大量值添加到现有字典中 - 最好是原生的?如果是这样,我们欢迎权威的“不”。
没有我想要的那么干净,但这是我知道的两种选择。
这个允许一次传递多个值,但需要创建一个新的Dictionary 而不是更新现有的:
Dictionary<string, string> newData = new Dictionary<string, string>(data)
{
{ "Key6", "Value6"},
{ "Key7", "Value7"},
{ "Key8", "Value8"},
};
也可以创建一个扩展方法,但这仍然为每一行调用Add:
public static void AddMany<Tkey, TValue>(this Dictionary<Tkey, TValue> dict, Dictionary<Tkey, TValue> toAdd)
{
foreach(KeyValuePair<Tkey, TValue> row in toAdd)
{
dict.Add(row.Key, row.Value);
}
}
【问题讨论】:
-
您在第一个示例中显示的语法实际上已被编译器修改为多次调用 Add,因此效果相同
-
@MatthewSteeples 作为初学者 C# 开发人员很高兴了解
标签: c# dictionary