Modifying Dictionaries
Coddy'nin C# Journey'sinin Mantık & Akış bölümünün bir parçası — ders 50 / 66.
C# dilindeki Dictionary'ler değiştirilebilir, yani onları oluşturduktan sonra değiştirebilirsiniz. Bir Dictionary'yi değiştirmenin yaygın yolları şunlardır:
Yeni bir anahtar-değer çifti ekleyin:
Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);Mevcut bir anahtarın değerini güncelleyin:
// Önce anahtarın var olup olmadığını kontrol edin
if (inventory.ContainsKey("apple"))
{
inventory["apple"] = 15; // "apple"ı değer 15'e günceller
}Bir anahtar-değer çifti kaldırın:
// "apple" girişini kaldır
inventory.Remove("apple");Tüm girişleri temizle:
// Tüm anahtar-değer çiftlerini kaldır
inventory.Clear();Görev
KolayUpdateInventory adında bir metot oluşturun ki üç argüman alsın:
- Envanteri temsil eden bir Dictionary<string, int>
- Bir öğe adını temsil eden bir string
- Yeni miktarı temsil eden bir int
Metot şunları yapmalıdır:
- Eğer öğe envanterde varsa, miktarını güncelleyin
- Eğer öğe mevcut değilse, verilen miktarla ekleyin
- Güncellenmiş envanteri şu formatta yazdırın: "Item: [quantity]" (her öğe bir satırda)
Kopya kağıdı
C#'ta Sözlükler değiştirilebilir ve oluşturulduktan sonra değiştirilebilir.
Yeni bir anahtar-değer çifti ekleyin:
Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);Mevcut bir anahtarın değerini güncelleyin:
// Önce anahtarın var olup olmadığını kontrol edin
if (inventory.ContainsKey("apple"))
{
inventory["apple"] = 15; // "apple"ı 15 değerine günceller
}Bir anahtar-değer çifti kaldırın:
// "apple" girişini kaldır
inventory.Remove("apple");Tüm girişleri temizleyin:
// Tüm anahtar-değer çiftlerini kaldır
inventory.Clear();Kendin dene
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
{
// Kodunuzu buraya yazın
// Güncellenmiş envanteri yazdırın
// Bunu kaldırmayın
foreach (KeyValuePair<string, int> entry in inventory)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
}
// Ana kodu yoksayın, string'i HashMap'e dönüştürür
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
// Read first line to check if it's JSON format
string firstLine = Console.ReadLine();
// Check if input is in JSON format
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// Process JSON input for initial inventory
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// Split by commas that are not inside quotes
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// Extract key and value using regex
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);
inventory.Add(keyMatch, valueMatch);
}
}
// Read the item to update and its quantity
string updateItemJson = Console.ReadLine();
// Check if update item is in JSON format with quotes
Match itemMatch = Regex.Match(updateItemJson, @"""([^""]+)""");
string updateItem = itemMatch.Success ? itemMatch.Groups[1].Value : updateItemJson;
int updateQuantity = int.Parse(Console.ReadLine());
UpdateInventory(inventory, updateItem, updateQuantity);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
else
{
try
{
// Process traditional input format
int initialCount = int.Parse(firstLine);
for (int i = 0; i < initialCount; i++)
{
string item = Console.ReadLine();
int quantity = int.Parse(Console.ReadLine());
inventory.Add(item, quantity);
}
// Read the item to update and its quantity
string updateItem = Console.ReadLine();
int updateQuantity = int.Parse(Console.ReadLine());
UpdateInventory(inventory, updateItem, updateQuantity);
}
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