Menu
CoddyTech

Métodos de HashMap

Parte de la sección Lógica y Flujo del Journey de C# de Coddy. Lección 52 de 66.

Los métodos de HashMap ofrecen formas eficaces de trabajar con los datos de tu diccionario. Exploremos algunos métodos comunes:

Comprueba si una clave existe en el diccionario:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);

bool hasApples = inventory.ContainsKey("apples");
// hasApples será true

Obtén todas las claves del diccionario:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

// Obtener todas las claves
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
    Console.WriteLine(name);
}

Obtén todos los valores del diccionario:

// Obtén todos los valores
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
    Console.WriteLine(score);
}

Elimina un elemento del diccionario:

scores.Remove("Bob");
// Dictionary ahora solo contiene la puntuación de Alice

Remove() devuelve true si la clave estaba allí y se eliminó, y false si no estaba. Eliminar una clave inexistente no es un error.

Vacía todos los elementos:

scores.Clear();
// El diccionario ahora está vacío

Obtén el número de elementos del diccionario usando .Count:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

int total = scores.Count;
Console.WriteLine(total);
// Salida: 2
challenge icon

Desafío

Intermedio

Crea un método llamado ProcessDictionary que tome un Dictionary<string, int> como argumento y realice las siguientes operaciones:

  1. Imprime Keys: seguido de todas las claves (una por línea)
  2. Imprime Values: seguido de todos los valores (uno por línea)
  3. Comprueba si el diccionario contiene la clave "total" e imprime Contains 'total': True o Contains 'total': False
  4. Elimina la clave "temp" si existe
  5. Imprime Count: seguido del número de elementos del diccionario después de estas operaciones (usa la propiedad .Count del diccionario)

Pruébalo tú mismo

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

class Program
{
    static void ProcessDictionary(Dictionary<string, int> dict)
    {
        // Escribe tu código aquí
    }
    // Ignora el código principal, convierte la cadena en un HashMap
    static void Main(string[] args)
    {
        Dictionary<string, int> inputDict = new Dictionary<string, int>();
        
        // Lee la primera línea para comprobar si tiene formato JSON
        string firstLine = Console.ReadLine();
        
        // Comprueba si la entrada tiene formato JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Procesa la entrada JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Separa por las comas que no están entre comillas
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extrae la clave y el valor mediante 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);
                        inputDict.Add(keyMatch, valueMatch);
                    }
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            try
            {
                // Process traditional input format
                int n = int.Parse(firstLine);
                
                for (int i = 0; i < n; i++)
                {
                    string[] pair = Console.ReadLine().Split(':');
                    string key = pair[0];
                    int value = int.Parse(pair[1]);
                    inputDict.Add(key, value);
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo

Practica por tu cuenta: Compilador de C# online