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

Definição

Adiciona um elemento com a chave e valor especificados no SortedList<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)

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 SortedList<TKey,TValue>.

Exemplos

O exemplo de código seguinte cria um vazio SortedList<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 SortedList<TKey,TValue> classe.

// Create a new sorted list of strings, with string
// keys.
SortedList<string, string> openWith =
    new SortedList<string, string>();

// Add some elements to the list. 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 list.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new sorted list of strings, with string 
' keys. 
Dim openWith As New SortedList(Of String, String)

' Add some elements to the list. 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 list.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
// Create a new sorted list of strings, with string
// keys.
let openWith = SortedList<string, string>()

// Add some elements to the list. 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 list.
try
    openWith.Add("txt", "winword.exe");
with
    | :? ArgumentException ->
        printfn "An element with Key = \"txt\" already exists."

Observações

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

Também pode usar a Item[] propriedade para adicionar novos elementos definindo o valor de uma chave que não existe no SortedList<TKey,TValue>; por exemplo, myCollection["myNonexistentKey"] = myValue. No entanto, se a chave especificada já existir no SortedList<TKey,TValue>, definindo a Item[] propriedade sobrescreve o valor antigo. Em contraste, o Add método não modifica elementos existentes.

Se Count já for Capacityigual a , a capacidade do SortedList<TKey,TValue> aumenta ao realocar automaticamente o array interno, e os elementos existentes são copiados para o novo array antes de o novo elemento ser adicionado.

Este método é uma operação O(n) para dados não ordenados, onde n é Count. É uma operação O(log n) se o novo elemento for adicionado no final da lista. Se a inserção causar um redimensionamento, a operação é O(n).

Aplica-se a

Ver também