Menu
Coddy logo textTech

Nested HashMap

Часть раздела Логика и управление потоком путешествия по C# на Coddy — урок 53 из 66.

Вложенная HashMap — это HashMap, где значения сами по себе являются HashMap. Это полезно для организации иерархических данных.

Создайте вложенную HashMap для хранения оценок студентов по предметам:

// Create the outer HashMap (student -> subjects)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Create an inner HashMap for a student (subject -> grade)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Add grades to the inner HashMap
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

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

Доступ к вложенному значению:

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

Добавьте еще одного студента с его оценками:

// Создайте еще один внутренний HashMap
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Добавьте в внешний HashMap
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Задание

Средне

Создайте метод с именем AddCourseGrade, который принимает четыре аргумента:

  1. Вложенный Dictionary, представляющий оценки студентов: Dictionary<string, Dictionary<string, int>> grades
  2. Имя студента (string)
  3. Имя курса (string)
  4. Оценка (int)

Метод должен:

  • Если студент не существует в словаре, создать для него новую запись
  • Добавить курс и оценку в запись студента
  • Если курс уже существует для этого студента, обновить оценку
  • Вывести "Added [course] grade for [student]: [grade]" после добавления/обновления

Шпаргалка

Вложенная HashMap — это HashMap, где значения сами по себе являются HashMap, полезная для организации иерархических данных.

Создание вложенной HashMap:

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);

Доступ к вложенным значениям:

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

Добавление другой записи:

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

Попробуйте сами

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)
    {
        // Напишите свой код здесь
    }
    
    // Игнорируйте основной код, он преобразует строку в HashMap
    static void Main(string[] args)
    {
        // Проверьте, может ли первая строка быть JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // Ввод в формате JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Разбор существующих оценок студентов из 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 iconПроверьте себя

В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.

Все уроки раздела Логика и управление потоком