SortedList<TKey,TValue>.Item[TKey] Propriété

Définition

Obtient ou définit la valeur associée à la clé spécifiée.

public:
 property TValue default[TKey] { TValue get(TKey key); void set(TKey key, TValue value); };
public TValue this[TKey key] { get; set; }
member this.Item('Key) : 'Value with get, set
Default Public Property Item(key As TKey) As TValue

Paramètres

key
TKey

Clé dont la valeur doit être obtenue ou définie.

Valeur de propriété

TValue

Valeur associée à la clé spécifiée. Si la clé spécifiée est introuvable, une opération Get retourne KeyNotFoundException et une opération Set crée un élément à l'aide de la clé spécifiée.

Implémente

Exceptions

key a la valeur null.

La propriété est récupérée et key n’existe pas dans la collection.

Exemples

L’exemple de code suivant utilise la Item[] propriété (l’indexeur en C#) pour récupérer des valeurs, démontrant qu’un KeyNotFoundException est levée lorsqu’une clé demandée n’est pas présente et montrant que la valeur associée à une clé peut être remplacée.

L’exemple montre également comment utiliser la TryGetValue méthode comme un moyen plus efficace de récupérer des valeurs si un programme doit souvent essayer des valeurs clés qui ne figurent pas dans la liste triée.

Cet exemple de code fait partie d’un exemple plus grand fourni pour la SortedList<TKey,TValue> classe .

// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console::WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console::WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
' The Item property is the default property, so you 
' can omit its name when accessing elements. 
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' The default Item property can be used to change the value
' associated with a key.
openWith("rtf") = "winword.exe"
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' If a key does not exist, setting the default Item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
printfn $"""For key = "rtf", value = {openWith["rtf"]}."""

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] <- "winword.exe"
printfn $"""For key = "rtf", value = {openWith["rtf"]}."""

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] <- "winword.exe";
// 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 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."
// 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", 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.
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."

Remarques

Cette propriété permet d'accéder à un élément spécifique dans la collection à l'aide de la syntaxe suivante : myCollection[key].

Une clé ne peut pas être null, mais une valeur peut être, si le type de valeurs dans la liste , TValueest un type de référence.

Si la clé est introuvable lors de la récupération d’une valeur, KeyNotFoundException est levée. Si la clé est introuvable lors de la définition d’une valeur, la clé et la valeur sont ajoutées.

Vous pouvez également utiliser la Item[] propriété pour ajouter de nouveaux éléments en définissant la valeur d’une clé qui n’existe pas dans ; SortedList<TKey,TValue>par exemple, myCollection["myNonexistentKey"] = myValue. Toutefois, si la clé spécifiée existe déjà dans , la SortedList<TKey,TValue>définition de la Item[] propriété remplace l’ancienne valeur. En revanche, la Add méthode ne modifie pas les éléments existants.

Le langage C# utilise le mot clé this pour définir les indexeurs au lieu d'implémenter la propriété Item[]. Visual Basic implémente Item[] comme propriété par défaut, ce qui fournit les mêmes fonctionnalités d'indexation.

La récupération de la valeur de cette propriété est une opération O(log n), où n est Count. La définition de la propriété est une opération O(log n) si la clé se trouve déjà dans .SortedList<TKey,TValue> Si la clé ne figure pas dans la liste, la définition de la propriété est une opération O(n) pour les données non triées, ou O(log n) si le nouvel élément est ajouté à la fin de la liste. Si l’insertion provoque un redimensionnement, l’opération est O(n).

S’applique à

Voir aussi