SortedDictionary<TKey,TValue>.Add(TKey, TValue) Metoda

Definicja

Dodaje element z określonym kluczem i wartością do elementu 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)

Parametry

key
TKey

Klucz elementu do dodania.

value
TValue

Wartość elementu do dodania. Wartość może być null dla typów referencyjnych.

Implementuje

Wyjątki

key to null.

Element o tym samym kluczu już istnieje w pliku SortedDictionary<TKey,TValue>.

Przykłady

Poniższy przykład kodu tworzy puste SortedDictionary<TKey,TValue> ciągi z kluczami ciągów i używa Add metody w celu dodania niektórych elementów. W przykładzie Add pokazano, że metoda zgłasza błąd ArgumentException podczas próby dodania zduplikowanego klucza.

Ten przykład kodu jest częścią większego przykładu udostępnionego SortedDictionary<TKey,TValue> dla klasy .

// 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

Uwagi

Możesz również użyć Item[] właściwości , aby dodać nowe elementy, ustawiając wartość klucza, który nie istnieje w elemecie SortedDictionary<TKey,TValue>, na przykład myCollection["myNonexistentKey"] = myValue (w Visual Basic, myCollection("myNonexistantKey") = myValue). Jeśli jednak określony klucz już istnieje w SortedDictionary<TKey,TValue>obiekcie , ustawienie Item[] właściwości zastępuje starą wartość. Z kolei metoda zgłasza wyjątek, Add jeśli element z określonym kluczem już istnieje.

Klucz nie może mieć nullwartości , ale wartość może być, jeśli typ wartości jest typem TValue referencyjnym.

Ta metoda jest operacją O(log n), gdzie n to Count.

Dotyczy

Zobacz też