Accessing Values
Coddy'nin C# Journey'sinin Mantık & Akış bölümünün bir parçası — ders 49 / 66.
C#'ta, HashMap'in eşdeğeri olarak Dictionary<TKey, TValue> kullanırız. Dictionary'ye öğeler ekledikten sonra, bunları geri almanız gerekecek.
String anahtarlar ve int değerlerle bir Dictionary oluşturun:
Dictionary<string, int> studentScores = new Dictionary<string, int>();Bazı girişler ekleyin:
studentScores.Add("John", 95);
studentScores.Add("Mary", 88);Bir anahtar kullanarak bir değere erişme:
int johnScore = studentScores["John"];Yukarıdaki kodu çalıştırdıktan sonra, johnScore şu değeri içerir:
95Dikkatli ol! Var olmayan bir anahtara erişmeye çalışırsan, KeyNotFoundException alırsın:
// Eğer "Bob" sözlükte yoksa bu bir istisna fırlatacak
int bobScore = studentScores["Bob"];Görev
KolayGetValueByKey adında iki parametre alan bir metot oluşturun:
- Dictionary<string, int> (sözlük).
- Aranacak bir string (anahtar).
Metot, verilen anahtar için değeri erişmeye çalışmalı ve:
- Anahtar varsa, değeri yazdırın.
- Anahtar yoksa, "Key not found" yazdırın.
Kopya kağıdı
string anahtarları ve int değerleri ile bir Sözlük oluşturun:
Dictionary<string, int> studentScores = new Dictionary<string, int>();Sözlük'e girişler ekleyin:
studentScores.Add("John", 95);
studentScores.Add("Mary", 88);Anahtar kullanarak bir değere erişin:
int johnScore = studentScores["John"];Var olmayan bir anahtara erişmek KeyNotFoundException fırlatacaktır:
// "Bob" sözlükte yoksa bir istisna fırlatacaktır
int bobScore = studentScores["Bob"];Kendin dene
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void GetValueByKey(Dictionary<string, int> dictionary, string key)
{
// Kodu buraya yazın
}
static void Main(string[] args)
{
// JSON formatında bir sözlük oku: {"key1":value1,"key2":value2}
string dictionaryInput = Console.ReadLine();
string key = Console.ReadLine();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// Sözlük oluşturmak için giriş dizesini ayrıştır
if (!string.IsNullOrEmpty(dictionaryInput))
{
try
{
// Girişin JSON formatında olup olmadığını kontrol et
if (dictionaryInput.StartsWith("{") && dictionaryInput.EndsWith("}"))
{
// Kök parantezleri kaldır
string jsonContent = dictionaryInput.Substring(1, dictionaryInput.Length - 2);
// Tırnaklar içinde olmayan virgüllerle böl
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// Regex kullanarak anahtar ve değeri çıkar
Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
if (match.Success)
{
string keyMatch = match.Groups[1].Value;
int valueMatch = int.Parse(match.Groups[2].Value);
dictionary.Add(keyMatch, valueMatch);
}
}
}
// Handle the original format "key1:value1,key2:value2" as fallback
else
{
string[] pairs = dictionaryInput.Split(',');
foreach (string pair in pairs)
{
string[] keyValue = pair.Split(':');
if (keyValue.Length == 2)
{
dictionary.Add(keyValue[0], int.Parse(keyValue[1]));
}
}
}
GetValueByKey(dictionary, key);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
}
}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 Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap