İç İçe HashMap
Coddy'nin C# Journey'sinin Mantık & Akış bölümünün bir parçası. Ders 53 / 66.
İç içe geçmiş bir HashMap, değerlerin kendilerinin HashMap olduğu bir HashMap'tir. Bu, hiyerarşik verileri düzenlemek için kullanışlıdır.
Öğrenci notlarını derse göre depolamak için iç içe bir HashMap oluşturun:
// Dış HashMap'i oluştur (öğrenci -> dersler)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
// Bir öğrenci için iç HashMap oluştur (ders -> not)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();
// Notları iç HashMap'e ekle
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);
// İç HashMap'i dış HashMap'e ekle
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 adlı ve dört bağımsız değişken alan bir yöntem oluşturun:
- Öğrenci notlarını temsil eden iç içe Dictionary:
Dictionary<string, Dictionary<string, int>> grades - Bir öğrenci adı (string)
- Bir ders adı (string)
- Bir not (int)
Yöntem şunları yapmalıdır:
- Öğrenci sözlükte yoksa öğrenci için yeni bir giriş oluşturun
- Dersi ve notu öğrencinin kaydına ekleyin
- Ders o öğrenci için zaten varsa notu güncelleyin
- Ekleme/güncelleme işleminden sonra "Added [course] grade for [student]: [grade]" yazdırın
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
1Çok Boyutlu Diziler
2B Dizilere Giriş2B Tanımlama ve Başlatma2B Dizi Öğelerine Erişim2B Dizilerle İç İçe DöngülerDüzensiz DizilerYaygın Matris İşlemleriTekrar - Çok Boyutlu4Akış Denetimi Teknikleri
Erken DönüşlerKoruma KoşullarıAtlama İfadeleri (goto)Break ve Continueİç İçe Koşulları Düzleştirme7İleri Düzey Mantıksal Operatörler
Kısa Devre DeğerlendirmesiKoşullu Mantıksal OperatörlerOperatör ÖnceliğiÖzet - İleri Düzey Operatörler2İleri Düzey Karar Verme
Birden Çok KoşulKarmaşık Boolean MantığıIf ve Switch Karşılaştırmasıİç İçe Switch İfadeleriÖzet - İleri Düzey Kararlar5İstisna Yönetimi
Try-Catch Temelleriİstisna TürleriBirden Çok Catch BloğuDosyalarla ÇalışmaFinally BloğuUsing ve Try-Finally KarşılaştırmasıÖzel İstisnalarTekrar - Hata Yönetimi3Döngü İyileştirmeleri
Döngü PerformansıKarmaşık Yapılar Üzerinde İterasyonHer Döngü TürüDöngüleri Yeniden DüzenlemeÖzet - Optimize Edilmiş Döngüler6Null Yönetimi
Null Referanslarının TemelleriNullable Değer TürleriNull Kontrolü DesenleriSavunmacı ProgramlamaTekrar - Null GüvenliğiKendi başına pratik yap: Online C# derleyicisi