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

Definição

Determina se o Dictionary<TKey,TValue> atual contém a chave especificada.

C#
public bool ContainsKey (TKey key);

Parâmetros

key
TKey

A chave a ser localizada no Dictionary<TKey,TValue>.

Retornos

true se o Dictionary<TKey,TValue> contiver um elemento com a chave especificada; caso contrário, false.

Implementações

Exceções

key é null.

Exemplos

O exemplo de código a seguir mostra como usar o ContainsKey método para testar se existe uma chave antes de chamar o Add método . Ele também mostra como usar o TryGetValue método para recuperar valores, que é uma maneira eficiente de recuperar valores quando um programa tenta frequentemente chaves que não estão no dicionário. Por fim, ele mostra a maneira menos eficiente de testar se as chaves existem, usando a Item[] propriedade (o indexador em C#).

Este exemplo de código faz parte de um exemplo maior fornecido para a Dictionary<TKey,TValue> classe (openWith é o nome do Dicionário usado neste exemplo).

C#
// ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
    Console.WriteLine("Value added for key = \"ht\": {0}",
        openWith["ht"]);
}
C#
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
C#
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

Comentários

Este método abrange uma operação O(1).

Aplica-se a

Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Confira também