Questo articolo è stato tradotto automaticamente. Per visualizzare l'articolo in inglese, selezionare la casella di controllo Inglese. È possibile anche visualizzare il testo inglese in una finestra popup posizionando il puntatore del mouse sopra il testo.

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


Data di pubblicazione: ottobre 2016

Determina se IDictionary<TKey, TValue> contiene un elemento con la chiave specificata.

Spazio dei nomi:   System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

bool ContainsKey(
	TKey key


Type: TKey

Chiave da individuare in IDictionary<TKey, TValue>.

Valore restituito

Type: System.Boolean

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

Exception Condition

key è null.

Implementations can vary in how they determine equality of objects; for example, the T:System.Collections.Generic.List`1 class uses P:System.Collections.Generic.Comparer`1.Default, whereas the T:System.Collections.Generic.Dictionary`2 class allows the user to specify the T:System.Collections.Generic.IComparer`1 implementation to use for comparing keys.

Implementations can vary in whether they allow key to be null.

The following code example shows how to use the M:System.Collections.Generic.IDictionary`2.ContainsKey(`0) method to test whether a key exists prior to calling the M:System.Collections.Generic.IDictionary`2.Add(`0,`1) method. It also shows how to use the M:System.Collections.Generic.IDictionary`2.TryGetValue(`0,`1@) method, which can be a more efficient way to retrieve values if a program frequently tries key values that are not in the dictionary. Finally, it shows how to insert items using P:System.Collections.Generic.IDictionary`2.Item(`0) property (the indexer in C#).

This code is part of a larger example that can be compiled and executed. See T:System.Collections.Generic.IDictionary`2.

// 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}", 
// 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);
    Console.WriteLine("Key = \"tif\" is not found.");
// The indexer throws an exception if the requested key is
// not in the dictionary.
    Console.WriteLine("For key = \"tif\", value = {0}.", 
catch (KeyNotFoundException)
    Console.WriteLine("Key = \"tif\" is not found.");

Universal Windows Platform
Disponibile da 8
.NET Framework
Disponibile da 2.0
Libreria di classi portabile
Supportato in: piattaforme .NET portabili
Disponibile da 2.0
Windows Phone Silverlight
Disponibile da 7.0
Windows Phone
Disponibile da 8.1
Torna all'inizio