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ề 90Thê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);Thử thách
Trung bìnhTạo một phương thức có tên AddCourseGrade nhận bốn đối số:
- Một từ điển lồng nhau biểu thị điểm của học sinh:
Dictionary<string, Dictionary<string, int>> grades - Tên học sinh (chuỗi)
- Tên khóa học (chuỗi)
- Đ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);
}
}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
1Mảng nhiều chiều
Cơ bản về mảng 2 chiềuKhai báo và khởi tạo mảng 2 chiềuTruy cập phần tử mảng 2 chiềuVòng lặp lồng nhau với mảng 2 chiềuMảng răng cưaCác phép toán ma trận thường gặpÔn tập: mảng nhiều chiều4Kỹ thuật điều khiển luồng
Lệnh trả về sớmMệnh đề bảo vệCâu lệnh nhảy (goto)Break và continueLàm phẳng các câu lệnh điều kiện lồng nhau7Toán tử logic nâng cao
Đánh giá ngắn mạchToán tử logic có điều kiệnĐộ ưu tiên của toán tửÔn tập: toán tử nâng cao10HashMap phần 2
Các phương thức của HashMapHashMap lồng nhauÔn tập: Quản lý kho hàngÔn tập: Các thao tác với HashMap2Ra quyết định nâng cao
Nhiều điều kiệnLogic Boolean phức tạpSo sánh if và switchCâu lệnh switch lồng nhauÔn tập về ra quyết định nâng cao5Xử lý ngoại lệ
Cơ bản về try-catchCác loại ngoại lệNhiều khối catchLàm việc với tệpKhối finallyUsing hay try-finallyNgoại lệ tùy chỉnhÔn tập: xử lý lỗi8Hệ thống phân tích dữ liệu
Thiết lập thu thập dữ liệuLogic nhập dữ liệu3Cải tiến vòng lặp
Hiệu suất vòng lặpLặp qua dữ liệu phức tạpTừng kiểu vòng lặpTái cấu trúc vòng lặpÔn tập: vòng lặp tối ưu6Xử lý null
Cơ bản về tham chiếu nullKiểu giá trị có thể nullCác mẫu kiểm tra nullLập trình phòng vệÔn tập về an toàn với nullTự luyện tập: Trình biên dịch C# online