Menu
Coddy logo textTech

HashMap anidado

Parte de la sección Lógica y Flujo del Journey de C# de Coddy. Lección 53 de 66.

Un HashMap anidado es un HashMap cuyos valores son, a su vez, HashMaps. Esto resulta útil para organizar datos jerárquicos.

Crea un HashMap anidado para almacenar las calificaciones de los estudiantes por asignatura:

// Crear el HashMap exterior (estudiante -> asignaturas)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Crear un HashMap interior para un estudiante (asignatura -> calificación)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Añadir calificaciones al HashMap interior
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Añadir el HashMap interior al HashMap exterior
studentGrades.Add("Alex", alexGrades);

Acceder a un valor anidado:

// Acceder a la calificación de Matemáticas de Alex
int mathGrade = studentGrades["Alex"]["Math"]; // Devuelve 90

Agregar otro estudiante con sus calificaciones:

// Crear otro HashMap interno
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Agregar al HashMap externo
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Desafío

Intermedio

Crea un método llamado AddCourseGrade que acepte cuatro argumentos:

  1. Un Dictionary anidado que representa las calificaciones de los estudiantes: Dictionary<string, Dictionary<string, int>> grades
  2. El nombre de un estudiante (string)
  3. El nombre de un curso (string)
  4. Una calificación (int)

El método debe:

  • Si el estudiante no existe en el diccionario, crear una nueva entrada para él
  • Agregar el curso y la calificación al registro del estudiante
  • Si el curso ya existe para ese estudiante, actualizar la calificación
  • Imprimir "Calificación de [course] agregada para [student]: [grade]" después de agregarla o actualizarla

Pruébalo tú mismo

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

class Program
{
    public static void AddCourseGrade(Dictionary<string, Dictionary<string, int>> grades, string student, string course, int grade)
    {
        // Escribe tu código aquí
    }
    
    // Ignora el código principal, convierte string a un HashMap
    static void Main(string[] args)
    {
        // Check if first line might be JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // JSON format input
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Parse existing student grades from JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                string studentPattern = @"""([^""]+)""\s*:\s*\{([^\}]+)\}";
                
                MatchCollection studentMatches = Regex.Matches(jsonContent, studentPattern);
                foreach (Match studentMatch in studentMatches)
                {
                    string studentName = studentMatch.Groups[1].Value;
                    string coursesJson = studentMatch.Groups[2].Value;
                    
                    Dictionary<string, int> courseGrades = new Dictionary<string, int>();
                    string coursePattern = @"""([^""]+)""\s*:\s*(\d+)";
                    
                    MatchCollection courseMatches = Regex.Matches(coursesJson, coursePattern);
                    foreach (Match courseMatch in courseMatches)
                    {
                        string courseName = courseMatch.Groups[1].Value;
                        int courseGrade = int.Parse(courseMatch.Groups[2].Value);
                        courseGrades.Add(courseName, courseGrade);
                    }
                    
                    studentGrades.Add(studentName, courseGrades);
                }
                
                // Parse student, course, and grade for the operation
                string studentInput = Console.ReadLine();
                Match studentNameMatch = Regex.Match(studentInput, @"""([^""]+)""");
                student = studentNameMatch.Success ? studentNameMatch.Groups[1].Value : studentInput;
                
                string courseInput = Console.ReadLine();
                Match courseNameMatch = Regex.Match(courseInput, @"""([^""]+)""");
                course = courseNameMatch.Success ? courseNameMatch.Groups[1].Value : courseInput;
                
                grade = int.Parse(Console.ReadLine());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            try
            {
                // Traditional input
                student = firstLine;
                course = Console.ReadLine();
                grade = int.Parse(Console.ReadLine());
                
                // Create an example entry
                Dictionary<string, int> johnGrades = new Dictionary<string, int>();
                johnGrades.Add("Math", 88);
                studentGrades.Add("John", johnGrades);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing traditional input: {ex.Message}");
                return;
            }
        }
        
        AddCourseGrade(studentGrades, student, course, grade);
    }
}
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

Practica por tu cuenta: Compilador de C# online