C#:Dictionary<TKey, TValue> em C#: operações com tabela hash
C#•Dicionários

Dictionary<TKey, TValue> em C#: operações com tabela hash

Aprenda buscas hash de alto desempenho em C# e padrões seguros de consulta com TryGetValue.

Sintaxe

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

Parâmetros e valores

Componentes principais e valores aceitos por esta estrutura:

ParâmetroTipoDescrição
TryGetValueMethodRecupera o valor com segurança sem lançar KeyNotFoundException.

Exemplo de código pronto para executar

Executável no Compilra

Execute este exemplo completo e funcional diretamente sem instalar C# localmente:

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}");
        }
    }
}
Saída esperada:
HTTPS is bound to port 443

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

Como funciona: passo a passo

  • Linhas 6-10: Inicializa Dictionary com sintaxe de inicializador por indexador do C#.
  • Linhas 17-19: TryGetValue recupera a porta com segurança sem lançar exceção.

Conceitos-chave

  • Dictionary oferece tempo médio O(1) para busca e inserção.
  • Acessar dict[missingKey] lança KeyNotFoundException; use TryGetValue ou ContainsKey.

Erro comum: Ler chave ausente usando o indexador dict[missingKey]

Ler uma chave inexistente lança KeyNotFoundException. Use TryGetValue em vez disso.

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

Tutoriais relacionados de C# e compilador

Execute e teste C# no Compilra

Execute este trecho de código com entrada padrão pré-fornecida (stdin) no compilador em nuvem do Compilra.

C# Compilador Online