嵌套 HashMap
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 53 课,共 66 课。
嵌套的 HashMap 是一种值本身也是 HashMap 的 HashMap。这有助于组织层次化数据。
创建一个嵌套的 HashMap,按科目存储学生成绩:
// 创建外层 HashMap(学生到科目的映射)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
// 为一名学生创建内层 HashMap(科目到成绩的映射)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();
// 将成绩添加到内层 HashMap
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);
// 将内层 HashMap 添加到外层 HashMap
studentGrades.Add("Alex", alexGrades);访问嵌套值:
// 获取 Alex 的 Math 成绩
int mathGrade = studentGrades["Alex"]["Math"]; // 返回 90再添加一名学生及其成绩:
// 创建另一个内层 HashMap
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);
// 添加到外层 HashMap
studentGrades.Add("Sarah", sarahGrades);挑战
中等创建一个名为 AddCourseGrade 的方法,它接受 4 个参数:
- 表示学生成绩的嵌套字典:
Dictionary<string, Dictionary<string, int>> grades - 学生姓名(字符串)
- 课程名称(字符串)
- 成绩(int)
该方法应:
- 如果字典中不存在该学生,就为其创建一个新条目
- 将课程和成绩添加到该学生的记录中
- 如果该学生的记录中已存在这门课程,就更新成绩
- 添加或更新后,打印 "Added [course] grade for [student]: [grade]"
亲手试试
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)
{
// 在这里编写你的代码
}
// 不用管 main 中的代码,它会把字符串转换为 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);
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器