Dictionary<TKey,TValue>.Add(TKey, TValue) Método

Definição

Adiciona a chave e o valor especificados ao dicionário.

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)

Parâmetros

key
TKey

A chave do elemento a ser adicionada.

value
TValue

O valor do elemento a ser adicionado. O valor pode ser null para tipos de referência.

Implementações

Exceções

key é null.

Já existe um elemento com a mesma chave no Dictionary<TKey,TValue>.

Exemplos

O exemplo de código a seguir cria um vazio Dictionary<TKey,TValue> de cadeias de caracteres com chaves de cadeia de caracteres e usa o Add método para adicionar alguns elementos. O exemplo demonstra que o Add método gera uma ArgumentException ao tentar adicionar uma chave duplicada.

Este exemplo de código faz parte de um exemplo maior fornecido para a Dictionary<TKey,TValue> classe.

// Create a new dictionary of strings, with string keys.
//
Dictionary<String^, String^>^ openWith =
    gcnew Dictionary<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 dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
    new Dictionary<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 dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(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

Comentários

Você também pode usar a Item[] propriedade para adicionar novos elementos definindo o valor de uma chave que não existe no Dictionary<TKey,TValue>; por exemplo, myCollection[myKey] = myValue (em Visual Basic, myCollection(myKey) = myValue). No entanto, se a chave especificada já existir no , definir Dictionary<TKey,TValue>a Item[] propriedade substituirá o valor antigo. Por outro lado, o Add método gerará uma exceção se já existir um valor com a chave especificada.

Se o valor da Count propriedade já for igual à capacidade, a capacidade do Dictionary<TKey,TValue> valor será aumentada realocando automaticamente a matriz interna e os elementos existentes serão copiados para a nova matriz antes que o novo elemento seja adicionado.

Uma chave não pode ser null, mas um valor pode ser, se TValue for um tipo de referência.

Se Count for menor que a capacidade, esse método se aproximará de uma operação O(1). Se a capacidade precisar ser aumentada para acomodar o novo elemento, esse método se tornará uma operação O(n), onde n está Count.

Aplica-se a

Confira também