Menu
Coddy logo textTech

Accessing Values

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 49 de 66.

En C#, usamos Dictionary<TKey, TValue> como el equivalente de HashMap. Después de agregar elementos a un Dictionary, necesitarás recuperarlos.

Crear un Dictionary con claves string y valores int:

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

Agrega algunas entradas:

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

Accediendo a un valor usando una clave:

int johnScore = studentScores["John"];

Después de ejecutar el código anterior, johnScore contiene:

95

¡Ten cuidado! Si intentas acceder a una clave que no existe, obtendrás una KeyNotFoundException:

// Esto lanzará una excepción si "Bob" no está en el diccionario
int bobScore = studentScores["Bob"];
challenge icon

Desafío

Fácil

Crea un método llamado GetValueByKey que tome dos argumentos:

  1. Un Dictionary<string, int> (diccionario).
  2. Una string (clave) para buscar.

El método debe intentar acceder al valor para la clave dada y:

  • Si la clave existe, imprime el valor.
  • Si la clave no existe, imprime "Key not found".

Hoja de referencia

Crear un Diccionario con claves de cadena y valores int:

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

Agregar entradas al Diccionario:

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

Acceder a un valor usando una clave:

int johnScore = studentScores["John"];

Acceder a una clave inexistente lanzará una KeyNotFoundException:

// Esto lanzará una excepción si "Bob" no está en el diccionario
int bobScore = studentScores["Bob"];

Pruébalo tú mismo

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

class Program
{
    public static void GetValueByKey(Dictionary<string, int> dictionary, string key)
    {
        // Escribe el código aquí
    }
    
    static void Main(string[] args)
    {
        // Lee un diccionario en formato JSON: {"key1":value1,"key2":value2}
        string dictionaryInput = Console.ReadLine();
        string key = Console.ReadLine();
        
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        
        // Analiza la cadena de entrada para crear un diccionario
        if (!string.IsNullOrEmpty(dictionaryInput))
        {
            try
            {
                // Comprueba si la entrada está en formato JSON
                if (dictionaryInput.StartsWith("{") && dictionaryInput.EndsWith("}"))
                {
                    // Elimina las llaves
                    string jsonContent = dictionaryInput.Substring(1, dictionaryInput.Length - 2);
                    
                    // Divide por comas que no estén dentro de comillas
                    string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                    string[] entries = Regex.Split(jsonContent, pattern);
                    
                    foreach (string entry in entries)
                    {
                        // Extrae la clave y el 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 iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo