Nested HashMap
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 53번째.
중첩된 HashMap은 값 자체가 HashMap인 HashMap입니다. 이것은 계층적 데이터를 구성하는 데 유용합니다.
과목별 학생 성적을 저장하기 위해 중첩된 HashMap을 생성하세요:
// 외부 HashMap 생성 (student -> subjects)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
// 학생을 위한 내부 HashMap 생성 (subject -> grade)
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을 반환또 다른 학생과 그들의 성적을 추가하세요:
// Create another inner HashMap
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);
// Add to the outer HashMap
studentGrades.Add("Sarah", sarahGrades);챌린지
중급이름이 AddCourseGrade인 메서드를 생성하세요. 이 메서드는 네 개의 인수를 받습니다:
- 학생 성적을 나타내는 중첩된 Dictionary:
Dictionary<string, Dictionary<string, int>> grades - 학생 이름 (string)
- 과목 이름 (string)
- 성적 (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);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety