Add Method

SortedDictionary(Of TKey, TValue).Add Method

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Adds an element with the specified key and value into the SortedDictionary(Of TKey, TValue).

Namespace:  System.Collections.Generic
Assembly:  System (in System.dll)

'Declaration
Public Sub Add ( _
	key As TKey, _
	value As TValue _
)

Parameters

key
Type: TKey
The key of the element to add.
value
Type: TValue
The value of the element to add. The value can be Nothing for reference types.

Implements

IDictionary(Of TKey, TValue).Add(TKey, TValue)

ExceptionCondition
ArgumentNullException

key is Nothing.

ArgumentException

An element with the same key already exists in the SortedDictionary(Of TKey, TValue).

You can also use the Item property to add new elements by setting the value of a key that does not exist in the SortedDictionary(Of TKey, TValue); for example, myCollection["myNonexistentKey"] = myValue (in Visual Basic, myCollection("myNonexistantKey") = myValue). However, if the specified key already exists in the SortedDictionary(Of TKey, TValue), setting the Item property overwrites the old value. In contrast, the Add method throws an exception if an element with the specified key already exists.

A key cannot be Nothing, but a value can be, if the value type TValue is a reference type.

This method is an O(log n) operation, where n is Count.

The following code example creates an empty SortedDictionary(Of TKey, TValue) of strings with string keys and uses the Add method to add some elements. The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

This code example is part of a larger example provided for the SortedDictionary(Of TKey, TValue) class.

Windows Phone OS

Supported in: 8.1, 8.0

Show:
© 2017 Microsoft