SortedDictionary<TKey,TValue>.Add(TKey, TValue) 方法

定义

将具有指定键和值的元素添加到 .SortedDictionary<TKey,TValue>

public:
 virtual void Add(TKey key, TValue value);
public void Add(TKey key, TValue value);
abstract member Add : 'Key * 'Value -> unit
override this.Add : 'Key * 'Value -> unit
Public Sub Add (key As TKey, value As TValue)

参数

key
TKey

要添加的元素的键。

value
TValue

要添加的元素的值。 该值可以 null 用于引用类型。

实现

例外

keynull

中已存在具有相同键的 SortedDictionary<TKey,TValue>元素。

示例

下面的代码示例创建包含字符串键的字符串的空 SortedDictionary<TKey,TValue> ,并使用 Add 该方法添加一些元素。 该示例演示该方法在 Add 尝试添加重复键时引发 ArgumentException

该代码示例是 SortedDictionary<TKey,TValue> 类中的一个较大示例的一部分。

// Create a new sorted dictionary of strings, with string
// keys.
SortedDictionary<string, string> openWith =
    new SortedDictionary<string, string>();

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new sorted dictionary of strings, with string 
' keys. 
Dim openWith As New SortedDictionary(Of String, String)

' Add some elements to the dictionary. There are no 
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")

' The Add method throws an exception if the new key is 
' already in the dictionary.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try

注解

还可以通过使用属性 Item[] 来添加新元素,方法是设置键 SortedDictionary<TKey,TValue>的值(例如 myCollection["myNonexistentKey"] = myValue ,在 Visual Basic myCollection("myNonexistantKey") = myValue中)。 但是,如果指定的键已存在于该属性中 SortedDictionary<TKey,TValue>,则设置该 Item[] 属性将覆盖旧值。 相反,如果具有指定键的元素已存在,该方法 Add 将引发异常。

如果值类型是引用类型null,则键不能TValue,但值可以是。

此方法是 O(logn) 操作,其中nCount

适用于

另请参阅