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 (ログ n) 操作であり、 nCount

適用対象

こちらもご覧ください