Menu
CoddyTech

HashMap lồng nhau

Thuộc phần Logic và luồng chương trình trong hành trình C# của Coddy. Bài học 53 trên 66.

HashMap lồng nhau là HashMap có các giá trị cũng là HashMap. Cách này hữu ích khi sắp xếp dữ liệu phân cấp.

Tạo một HashMap lồng nhau để lưu điểm của học sinh theo môn học:

// Tạo HashMap bên ngoài (học sinh -> các môn học)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Tạo HashMap bên trong cho một học sinh (môn học -> điểm)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Thêm điểm vào HashMap bên trong
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Thêm HashMap bên trong vào HashMap bên ngoài
studentGrades.Add("Alex", alexGrades);

Truy cập một giá trị lồng nhau:

// Truy cập điểm môn Toán của Alex
int mathGrade = studentGrades["Alex"]["Math"]; // Trả về 90

Thêm một học sinh khác cùng điểm số:

// Tạo thêm một HashMap bên trong
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Thêm vào HashMap bên ngoài
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Thử thách

Trung bình

Tạo một phương thức có tên AddCourseGrade nhận bốn đối số:

  1. Một từ điển lồng nhau biểu thị điểm của học sinh: Dictionary<string, Dictionary<string, int>> grades
  2. Tên học sinh (chuỗi)
  3. Tên khóa học (chuỗi)
  4. Điểm (int)

Phương thức này cần:

  • Nếu học sinh chưa có trong từ điển, hãy tạo một mục mới cho học sinh đó
  • Thêm khóa học và điểm vào hồ sơ của học sinh
  • Nếu học sinh đó đã có khóa học này, hãy cập nhật điểm
  • In ra "Added [course] grade for [student]: [grade]" sau khi thêm hoặc cập nhật

Tự làm thử

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)
    {
        // Viết code của bạn ở đây
    }
    
    // Bỏ qua đoạn code chính, nó chuyển chuỗi thành HashMap
    static void Main(string[] args)
    {
        // Kiểm tra xem dòng đầu tiên có phải là JSON không
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // Đầu vào ở định dạng JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Phân tích điểm hiện có của học sinh từ 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 iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Logic và luồng chương trình

Tự luyện tập: Trình biên dịch C# online