.NET Framework 添加到字典

示例

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "First");
dict.Add(2, "Second");

// 为了安全地添加项目(检查以确保该项目尚不存在-会抛出)
if(!dict.ContainsKey(3))
{
   dict.Add(3, "Third");
}

或者,可以通过索引器添加/设置它们。(索引器在内部看起来像一个属性,具有一个get和set,但是采用括号之间指定的任何类型的参数):

Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "First";
dict[2] = "Second";
dict[3] = "Third";

与Add引发异常的方法不同,如果字典中已包含键,则索引器将替换现有值。

对于线程安全字典,请使用ConcurrentDictionary<TKey, TValue>:

var dict = new ConcurrentDictionary<int, string>();
dict.AddOrUpdate(1, "First", (oldKey, oldValue) => "First");