C#:Dictionary<TKey, TValue> en C# : opérations sur tables de hachage
C#•Dictionnaires

Dictionary<TKey, TValue> en C# : opérations sur tables de hachage

Découvrez les recherches par hachage performantes en C# et les modèles sûrs avec TryGetValue.

Syntaxe

var dict = new Dictionary<string, int>(); dict["key"] = 100; dict.TryGetValue("key", out int val);

Paramètres et valeurs

Composants clés et valeurs acceptées pour cette structure :

ParamètreTypeDescription
TryGetValueMethodRécupère une valeur en toute sécurité sans lever KeyNotFoundException.

Exemple de code prêt à exécuter

Exécutable dans Compilra

Exécutez cet exemple complet directement sans installer C# localement :

using System;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var portRegistry = new Dictionary<string, int> {
            ["HTTP"] = 80,
            ["HTTPS"] = 443,
            ["SSH"] = 22
        };

        // Adding entries
        portRegistry["REDIS"] = 6379;

        // Safe lookup with TryGetValue
        string queryProtocol = "HTTPS";
        if (portRegistry.TryGetValue(queryProtocol, out int port)) {
            Console.WriteLine($"{queryProtocol} is bound to port {port}");
        }

        Console.WriteLine("\nAll Registered Ports:");
        foreach (var kvp in portRegistry) {
            Console.WriteLine($"  {kvp.Key} -> {kvp.Value}");
        }
    }
}
Sortie attendue :
HTTPS is bound to port 443

All Registered Ports:
  HTTP -> 80
  HTTPS -> 443
  SSH -> 22
  REDIS -> 6379

Fonctionnement étape par étape

  • Lignes 6-10: Initialise Dictionary avec la syntaxe d’initialiseur d’indexeur C#.
  • Lignes 17-19: TryGetValue récupère le port en sécurité sans lever d’exception.

Concepts clés

  • Dictionary offre un temps moyen de recherche et d’insertion en O(1).
  • Accéder à dict[missingKey] lève KeyNotFoundException ; utilisez TryGetValue ou ContainsKey.

Erreur fréquente : Lire une clé absente avec l’indexeur dict[missingKey]

Lire une clé inexistante lève KeyNotFoundException. Utilisez TryGetValue à la place.

❌ Incorrect
int p = portRegistry["UNKNOWN"]; // Throws KeyNotFoundException!
✅ Correct
portRegistry.TryGetValue("UNKNOWN", out int p); // Safe

Tutoriels C# associés et compilateur

Exécutez et testez C# sur Compilra

Exécutez cet extrait de code avec une entrée standard pré-fournie (stdin) dans le compilateur cloud de Compilra.

C# Compilateur en ligne