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

Definición

Obtiene el valor asociado a la clave especificada.

public:
 virtual bool TryGetValue(TKey key, [Runtime::InteropServices::Out] TValue % value);
public bool TryGetValue(TKey key, out TValue value);
abstract member TryGetValue : 'Key * 'Value -> bool
override this.TryGetValue : 'Key * 'Value -> bool
Public Function TryGetValue (key As TKey, ByRef value As TValue) As Boolean

Parámetros

key
TKey

Clave cuyo valor se va a obtener.

value
TValue

Cuando este método devuelve, el valor asociado a la clave especificada, si se encuentra la clave; de lo contrario, el valor predeterminado para el tipo del value parámetro . Este parámetro se pasa sin inicializar.

Devoluciones

true SortedList<TKey,TValue> si contiene un elemento con la clave especificada; de lo contrario, false.

Implementaciones

Excepciones

key es null.

Ejemplos

En el ejemplo se muestra cómo usar el TryGetValue método como una manera más eficaz de recuperar valores en un programa que intenta con frecuencia claves que no están en la lista ordenada. Por el contrario, en el ejemplo también se muestra cómo la Item[] propiedad (el indizador en C#) produce excepciones al intentar recuperar claves inexistentes.

Este ejemplo de código forma parte de un ejemplo más grande proporcionado para la SortedList<TKey,TValue> clase .

// When a program often has to try keys that turn out not to
// be in the list, 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 list, 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
// When a program often has to try keys that turn out not to
// be in the list, TryGetValue can be a more efficient
// way to retrieve values.
match openWith.TryGetValue("tif") with
| true, value ->
    printfn "For key = \"tif\", value = {value}."
| false, _ ->
    printfn "Key = \"tif\" is not found."
// The indexer throws an exception if the requested key is
// not in the list.
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 list.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// The indexer throws an exception if the requested key is
// not in the list.
try
    printfn $"""For key = "tif", value = {openWith["tif"]}."""
with 
    | :? KeyNotFoundException ->
        printfn "Key = \"tif\" is not found."

Comentarios

Este método combina la funcionalidad del ContainsKey método y la Item[] propiedad .

Si no se encuentra la clave, el value parámetro obtiene el valor predeterminado adecuado para el tipo TValuede valor ; por ejemplo, cero (0) para los tipos enteros, false para los tipos booleanos y null para los tipos de referencia.

Este método realiza una búsqueda binaria; por lo tanto, este método es una operación de O(log n), donde n es Count.

Se aplica a

Consulte también