Menu
Coddy logo textTech

HashMap annidate

Fa parte della sezione Logica e flusso del percorso C# di Coddy. Lezione 53 di 66.

Una HashMap annidata è una HashMap in cui i valori stessi sono HashMap. È utile per organizzare dati gerarchici.

Crea una HashMap annidata per memorizzare i voti degli studenti per materia:

// Crea l'HashMap esterna (studente -> materie)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Crea un'HashMap interna per uno studente (materia -> voto)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Aggiungi i voti all'HashMap interna
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Aggiungi l'HashMap interna all'HashMap esterna
studentGrades.Add("Alex", alexGrades);

Accedi a un valore annidato:

// Accedi al voto di Alex in Math
int mathGrade = studentGrades["Alex"]["Math"]; // Restituisce 90

Aggiungi un altro studente con i suoi voti:

// Crea un'altra HashMap interna
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Aggiungi alla HashMap esterna
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Sfida

Medio

Crea un metodo denominato AddCourseGrade che accetta quattro argomenti:

  1. Un Dictionary annidato che rappresenta i voti degli studenti: Dictionary<string, Dictionary<string, int>> grades
  2. Il nome di uno studente (stringa)
  3. Il nome di un corso (stringa)
  4. Un voto (int)

Il metodo dovrebbe:

  • Se lo studente non esiste nel dizionario, creare una nuova voce per lui
  • Aggiungere il corso e il voto al record dello studente
  • Se il corso esiste già per quello studente, aggiornare il voto
  • Stampare "Added [course] grade for [student]: [grade]" dopo aver aggiunto/aggiornato

Provalo tu

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)
    {
        // Scrivi il tuo codice qui
    }
    
    // Ignora il codice principale: converte una stringa in una HashMap
    static void Main(string[] args)
    {
        // Controlla se la prima riga potrebbe essere JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // Input in formato JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Analizza i voti degli studenti già presenti nel 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 iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore C# online