Menu
Coddy logo textTech

Accessing Values

Parte da seção Lógica & Fluxo do Journey de C# da Coddy — lição 49 de 66.

Em C#, usamos Dictionary<TKey, TValue> como o equivalente de HashMap. Após adicionar itens a um Dictionary, você precisará recuperá-los.

Crie um Dictionary com chaves string e valores int:

Dictionary<string, int> studentScores = new Dictionary<string, int>();

Adicione algumas entradas:

studentScores.Add("John", 95);
studentScores.Add("Mary", 88);

Acessando um valor usando uma chave:

int johnScore = studentScores["John"];

Após executar o código acima, johnScore contém:

95

Cuidado! Se você tentar acessar uma chave que não existe, você receberá uma KeyNotFoundException:

// This will throw an exception if "Bob" isn't in the dictionary
int bobScore = studentScores["Bob"];
challenge icon

Desafio

Fácil

Crie um método chamado GetValueByKey que recebe dois argumentos:

  1. Um Dictionary<string, int> (dicionário).
  2. Uma string (chave) para consultar.

O método deve tentar acessar o valor para a chave dada e:

  • Se a chave existir, imprima o valor.
  • Se a chave não existir, imprima "Key not found".

Folha de consulta

Crie um Dicionário com chaves string e valores int:

Dictionary<string, int> studentScores = new Dictionary<string, int>();

Adicione entradas ao Dicionário:

studentScores.Add("John", 95);
studentScores.Add("Mary", 88);

Acesse um valor usando uma chave:

int johnScore = studentScores["John"];

Acessar uma chave inexistente lançará uma KeyNotFoundException:

// Isso lançará uma exceção se "Bob" não estiver no dicionário
int bobScore = studentScores["Bob"];

Experimente você mesmo

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    public static void GetValueByKey(Dictionary<string, int> dictionary, string key)
    {
        // Escreva o código aqui
    }
    
    static void Main(string[] args)
    {
        // Lê um dicionário no formato JSON: {"key1":value1,"key2":value2}
        string dictionaryInput = Console.ReadLine();
        string key = Console.ReadLine();
        
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        
        // Analisa a string de entrada para criar um dicionário
        if (!string.IsNullOrEmpty(dictionaryInput))
        {
            try
            {
                // Verifica se a entrada está no formato JSON
                if (dictionaryInput.StartsWith("{") && dictionaryInput.EndsWith("}"))
                {
                    // Remove as chaves
                    string jsonContent = dictionaryInput.Substring(1, dictionaryInput.Length - 2);
                    
                    // Divide por vírgulas que não estão dentro de aspas
                    string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                    string[] entries = Regex.Split(jsonContent, pattern);
                    
                    foreach (string entry in entries)
                    {
                        // Extrai a chave e o valor usando regex
                        Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
                        if (match.Success)
                        {
                            string keyMatch = match.Groups[1].Value;
                            int valueMatch = int.Parse(match.Groups[2].Value);
                            dictionary.Add(keyMatch, valueMatch);
                        }
                    }
                }
                // Handle the original format "key1:value1,key2:value2" as fallback
                else
                {
                    string[] pairs = dictionaryInput.Split(',');
                    foreach (string pair in pairs)
                    {
                        string[] keyValue = pair.Split(':');
                        if (keyValue.Length == 2)
                        {
                            dictionary.Add(keyValue[0], int.Parse(keyValue[1]));
                        }
                    }
                }
                
                GetValueByKey(dictionary, key);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Lógica & Fluxo