שינוי מילונים
חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-C# של Coddy. שיעור 50 מתוך 66.
מילונים ב-C# ניתנים לשינוי, כלומר אפשר לשנות אותם לאחר יצירתם. הנה הדרכים הנפוצות לשינוי מילון:
הוסיפו זוג מפתח-ערך חדש:
Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);עדכן את הערך של מפתח קיים:
// תחילה בודקים אם המפתח קיים
if (inventory.ContainsKey("apple"))
{
inventory["apple"] = 15; // מעדכן את "apple" כך שערכו יהיה 15
}הסרת זוג מפתח-ערך:
// הסר את הערך "apple"
inventory.Remove("apple");נקה את כל הרשומות:
// הסר את כל זוגות המפתח-ערך
inventory.Clear();אתגר
קלצרו מתודה בשם UpdateInventory שמקבלת שלושה ארגומנטים:
- Dictionary<string, int> שמייצג מלאי
- מחרוזת שמייצגת שם של פריט
- int שמייצג את הכמות החדשה
המתודה צריכה:
- אם הפריט קיים במלאי, לעדכן את הכמות שלו
- אם הפריט לא קיים, להוסיף אותו עם הכמות הנתונה
- להדפיס את המלאי המעודכן בפורמט: "Item: [quantity]" (פריט אחד בכל שורה)
נסו בעצמכם
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
{
// כתבו את הקוד שלכם כאן
// הדפיסו את המלאי המעודכן
// אל תסירו את זה
foreach (KeyValuePair<string, int> entry in inventory)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
}
// התעלמו מהקוד הראשי, הוא ממיר מחרוזת ל-HashMap
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
// קראו את השורה הראשונה כדי לבדוק אם היא בפורמט JSON
string firstLine = Console.ReadLine();
// בדקו אם הקלט בפורמט JSON
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// עבדו את קלט ה-JSON עבור המלאי ההתחלתי
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// פצלו לפי פסיקים שאינם בתוך מרכאות
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// חלצו מפתח וערך באמצעות 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}");
}
}
}
}השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.
כל השיעורים ביחידה לוגיקה וזרימת תוכנית
1מערכים רב־ממדיים
יסודות מערכים דו־ממדייםהכרזה ואתחול של מערכים דו־ממדייםגישה לאיברי מערך דו־ממדילולאות מקוננות עם מערכים דו־ממדייםמערכים משונניםפעולות מטריצה נפוצותחזרה – מערכים רב־ממדיים7אופרטורים לוגיים מתקדמים
הערכה בקיצור דרךאופרטורים לוגיים מותניםקדימות אופרטוריםסיכום – אופרטורים מתקדמים2קבלת החלטות מתקדמת
תנאים מרוביםלוגיקה בוליאנית מורכבתהשוואה בין If ל-Switchהצהרות Switch מקוננותסיכום — קבלת החלטות מתקדמת5טיפול בחריגות
יסודות try-catchסוגי חריגותבלוקי catch מרוביםעבודה עם קבציםבלוק finallyשימוש ב-using לעומת try-finallyחריגות מותאמות אישיתסיכום – טיפול בשגיאות3שיפורים בלולאות
ביצועי לולאותאיטרציה במבנים מורכביםכל אחד מסוגי הלולאותרפקטורינג של לולאותסיכום – לולאות שעברו אופטימיזציה6טיפול בערכי Null
יסודות הפניה ל-Nullטיפוסי ערכים שניתנים ל-Nullדפוסי בדיקת Nullתכנות הגנתיסיכום – בטיחות מול Null9מפת גיבוב חלק 1
מהי מפת גיבוב?הכרזה על מפת גיבובבדיקה אם מפתח קייםגישה לערכיםשינוי מילוניםסיכום – מפת גיבובתרגלו בעצמכם: קומפיילר C# אונליין