Nested HashMap
Coddy'nin C# Journey'sinin Mantık & Akış bölümünün bir parçası — ders 53 / 66.
İç içe bir HashMap, değerlerin kendileri HashMap'ler olduğu bir HashMap'tir. Bu, hiyerarşik verileri organize etmek için kullanışlıdır.
Derslere göre öğrenci notlarını saklamak için iç içe bir HashMap oluşturun:
// Dış HashMap'i oluşturun (öğrenci -> dersler)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
// Bir öğrenci için iç HashMap oluşturun (ders -> not)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();
// İç HashMap'e notlar ekleyin
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);
// İç HashMap'i dış HashMap'e ekleyin
studentGrades.Add("Alex", alexGrades);İç içe bir değere erişin:
// Alex'in Matematik notuna erişin
int mathGrade = studentGrades["Alex"]["Math"]; // 90 döndürürBaşka bir öğrenciyi notlarıyla birlikte ekleyin:
// 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);Görev
OrtaAddCourseGrade adında dört argüman alan bir yöntem oluşturun:
- Öğrenci notlarını temsil eden iç içe bir Dictionary:
Dictionary<string, Dictionary<string, int>> grades - Bir öğrenci adı (string)
- Bir ders adı (string)
- Bir not (int)
Yöntem şu işlemleri yapmalıdır:
- Eğer öğrenci sözlükte yoksa, onlar için yeni bir giriş oluşturun
- Dersi ve notu öğrencinin kaydına ekleyin
- Eğer o öğrenci için ders zaten varsa, notu güncelleyin
- Ekledikten/güncelledikten sonra "Added [course] grade for [student]: [grade]" yazdırın
Kopya kağıdı
İç içe bir HashMap, değerlerin kendilerinin HashMap'ler olduğu bir HashMap'tir ve hiyerarşik verileri organize etmek için kullanışlıdır.
İç içe bir HashMap oluşturun:
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);İç içe değerlere erişin:
int mathGrade = studentGrades["Alex"]["Math"]; // Returns 90Başka bir giriş ekleyin:
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);
studentGrades.Add("Sarah", sarahGrades);Kendin dene
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)
{
// Kodunuzu buraya yazın
}
// Ana kodu görmezden gelin, dizeyi bir HashMap'e dönüştürür
static void Main(string[] args)
{
// İlk satırın JSON olup olmadığını kontrol edin
string firstLine = Console.ReadLine();
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
string student;
string course;
int grade;
// JSON formatında girdi
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// Mevcut öğrenci notlarını JSON'dan ayrıştırın
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);
}
}Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
Mantık & Akış bölümündeki tüm dersler
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