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âmetro | Tipo | Descrição |
|---|---|---|
| TryGetValue | Method | Recupera o valor com segurança sem lançar KeyNotFoundException. |
Exemplo de código pronto para executar
Executável no CompilraExecute 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); // SafeTutoriais relacionados de C# e compilador
List<T> em C# e consultas LINQ: Where, Select e Aggregate
Domine coleções dinâmicas List<T> e consultas LINQ poderosas (Where, Select, Sum).
HashSet<T> e ValueTuples em C# (múltiplos valores de retorno)
Remova duplicados com HashSet<T> e retorne múltiplos valores usando ValueTuples leves.
Métodos de string, interpolação e StringBuilder em C#
Domine manipulação de texto com métodos de string, literais brutos e StringBuilder.
C# Compilador Online
Abrir na IDE Compilra
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.