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

Definizione

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

public:
 virtual bool ContainsKey(TKey key);
public bool ContainsKey (TKey key);
abstract member ContainsKey : 'Key -> bool
override this.ContainsKey : 'Key -> bool
Public Function ContainsKey (key As TKey) As Boolean

Parametri

key
TKey

Chiave da individuare in SortedDictionary<TKey,TValue>.

Restituisce

true se SortedDictionary<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. Viene inoltre illustrato come usare il TryGetValue metodo per recuperare i valori, che è un modo efficiente per recuperare i valori quando un programma prova spesso le chiavi che non si trovano nel dizionario. Infine, mostra il modo meno efficiente per verificare se esistono chiavi, usando la proprietà (l'indicizzatore Item[] in C#).

Questo esempio di codice fa parte di un esempio più grande fornito per la SortedDictionary<TKey,TValue> classe.

// 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"]);
}
' ContainsKey can be used to test keys before inserting 
' them.
If Not openWith.ContainsKey("ht") Then
    openWith.Add("ht", "hypertrm.exe")
    Console.WriteLine("Value added for key = ""ht"": {0}", _
        openWith("ht"))
End If
// 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.");
}
' 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.
Dim value As String = ""
If openWith.TryGetValue("tif", value) Then
    Console.WriteLine("For key = ""tif"", value = {0}.", value)
Else
    Console.WriteLine("Key = ""tif"" is not found.")
End If
// 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.");
}
' The default Item property throws an exception if the requested
' key is not in the dictionary.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try

Commenti

Questo metodo è un'operazione O(log n).

Si applica a

Vedi anche