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 adicionar.

value
TValue

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

Implementações

Exceções

key é null.

Um elemento com a mesma chave já existe no Dictionary<TKey,TValue>.

Exemplos

O exemplo de código seguinte cria um vazio Dictionary<TKey,TValue> de strings com chaves string e usa o Add método para adicionar alguns elementos. O exemplo demonstra que o Add método lança um 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 =
    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.
let openWith = 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")
with :? ArgumentException ->
    printfn "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

Observações

Também pode usar a propriedade Item[] 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 Dictionary<TKey,TValue>, definindo a Item[] propriedade sobrescreve o valor antigo. Em contraste, o Add método lança uma exceção se já existir um valor com a chave especificada.

Se o Count valor da propriedade já for igual à capacidade, a capacidade do Dictionary<TKey,TValue> é aumentada ao realocar automaticamente o array interno, e os elementos existentes são copiados para o novo array antes de o novo elemento ser 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, este método aproxima-se de uma operação O(1). Se a capacidade tiver de ser aumentada para acomodar o novo elemento, este método torna-se uma operação O(n), onde n é Count.

Aplica-se a

Ver também