Menu
Coddy logo textTech

Modifier des dictionnaires

Fait partie de la section Logique & Flux du Journey C# de Coddy — leçon 50 sur 66.

Les dictionnaires en C# sont mutables, ce qui signifie que vous pouvez les modifier après les avoir créés. Voici les moyens courants pour modifier un Dictionary :

Ajouter une nouvelle paire clé-valeur :

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);

Mettre à jour la valeur d'une clé existante :

// Vérifier d'abord si la clé existe
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // Met à jour "apple" pour avoir la valeur 15
}

Supprimer une paire clé-valeur :

// Remove the "apple" entry
inventory.Remove("apple");

Effacer toutes les entrées :

// Supprimer toutes les paires clé-valeur
inventory.Clear();
challenge icon

Défi

Facile

Créez une méthode nommée UpdateInventory qui prend trois arguments :

  1. Une Dictionary<string, int> représentant un inventaire
  2. Une chaîne représentant le nom d'un article
  3. Un int représentant la nouvelle quantité

La méthode devrait :

  • Si l'article existe dans l'inventaire, mettez à jour sa quantité
  • Si l'article n'existe pas, ajoutez-le avec la quantité donnée
  • Imprimez l'inventaire mis à jour au format : "Item: [quantity]" (un article par ligne)

Aide-mémoire

Les dictionnaires en C# sont modifiables et peuvent être modifiés après leur création.

Ajouter une nouvelle paire clé-valeur :

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);

Mettre à jour la valeur d'une clé existante :

// First check if key exists
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // Updates "apple" to have value 15
}

Supprimer une paire clé-valeur :

// Remove the "apple" entry
inventory.Remove("apple");

Effacer toutes les entrées :

// Remove all key-value pairs
inventory.Clear();

Essayez vous-même

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
    {
        // Écrivez votre code ici
        
        // Affichez l'inventaire mis à jour
        // Ne supprimez pas ceci
        foreach (KeyValuePair<string, int> entry in inventory)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
    // Ignorez le code principal, il convertit une chaîne en HashMap
    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}");
            }
        }
    }
}
quiz iconTestez-vous

Cette leçon comprend un petit quiz. Commencez la leçon pour y répondre et suivre votre progression.

Toutes les leçons de Logique & Flux