Menu
Coddy logo textTech

Nested HashMap

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

Um HashMap aninhado é um HashMap onde os valores em si são HashMaps. Isso é útil para organizar dados hierárquicos.

Crie um HashMap aninhado para armazenar as notas dos alunos por matéria:

// Crie o HashMap externo (aluno -> matérias)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Crie um HashMap interno para um aluno (matéria -> nota)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Adicione as notas ao HashMap interno
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Adicione o HashMap interno ao HashMap externo
studentGrades.Add("Alex", alexGrades);

Acessar um valor aninhado:

// Access Alex's Math grade
int mathGrade = studentGrades["Alex"]["Math"]; // Returns 90

Adicione outro aluno com suas notas:

// Create another inner HashMap
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Add to the outer HashMap
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Desafio

Médio

Crie um método chamado AddCourseGrade que recebe quatro argumentos:

  1. Um Dictionary aninhado representando as notas dos alunos: Dictionary<string, Dictionary<string, int>> grades
  2. Um nome de aluno (string)
  3. Um nome de curso (string)
  4. Uma nota (int)

O método deve:

  • Se o aluno não existir no dicionário, crie uma nova entrada para ele
  • Adicione o curso e a nota ao registro do aluno
  • Se o curso já existir para esse aluno, atualize a nota
  • Imprima "Added [course] grade for [student]: [grade]" após adicionar/atualizar

Folha de consulta

Um HashMap aninhado é um HashMap onde os valores em si são HashMaps, útil para organizar dados hierárquicos.

Crie um HashMap aninhado:

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

// Create inner HashMap
Dictionary<string, int> alexGrades = new Dictionary<string, int>();
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Add to outer HashMap
studentGrades.Add("Alex", alexGrades);

Acesse valores aninhados:

int mathGrade = studentGrades["Alex"]["Math"]; // Returns 90

Adicione outra entrada:

Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);
studentGrades.Add("Sarah", sarahGrades);

Experimente você mesmo

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)
    {
        // Escreva seu código aqui
    }
    
    // Ignore o código principal, ele converte string para um HashMap
    static void Main(string[] args)
    {
        // Verifique se a primeira linha pode ser JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // Entrada no formato JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Analise as notas existentes dos alunos a partir do 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 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