Dictionary<TKey,TValue>.ContainsKey(TKey) Metodo

Definizione

Determina se la raccolta Dictionary<TKey,TValue> contiene la chiave specificata.

C#
public bool ContainsKey (TKey key);

Parametri

key
TKey

Chiave da individuare in Dictionary<TKey,TValue>.

Restituisce

true se Dictionary<TKey,TValue> contiene un elemento con la chiave specificata; in caso contrario, false.

Implementazioni

Eccezioni

key è null.

Esempio

Nell'esempio di codice seguente viene illustrato come usare il ContainsKey metodo per verificare se esiste una chiave prima di chiamare il Add metodo . Illustra anche come usare il TryGetValue metodo per recuperare i valori, che è un modo efficiente per recuperare i valori quando un programma tenta spesso le chiavi che non si trovano nel dizionario. Infine, mostra il modo meno efficiente per verificare se esistono chiavi usando la Item[] proprietà (l'indicizzatore in C#).

Questo esempio di codice fa parte di un esempio più ampio fornito per la Dictionary<TKey,TValue> classe (openWith è il nome del dizionario usato in questo esempio).

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.");
}

Commenti

Questo metodo si avvicina a un'operazione O(1).

Si applica a

Prodotto Versioni
.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

Vedi anche