Menu
Coddy logo textTech

Declare a HashMap

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 47 de 66.

En C#, el equivalente de un HashMap se llama Dictionary. Permite almacenar pares clave-valor para una búsqueda eficiente.

Primero, vamos a crear un Dictionary vacío:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>();

Esto crea un Diccionario donde las claves son strings (nombres de frutas) y los valores son enteros (cantidad).

Ahora, agreguemos algunos elementos a nuestro Dictionary:

fruitInventory.Add("Apple", 10);
fruitInventory.Add("Banana", 15);

Después de ejecutar el código anterior, nuestro fruitInventory contiene:

  • "Apple" → 10
  • "Banana" → 15

También puedes inicializar un Dictionary con valores:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>()
{
    { "Apple", 10 },
    { "Banana", 15 }
};
challenge icon

Desafío

Intermedio

Crea un método llamado CreateFruitInventory que:

  1. Cree un nuevo Dictionary con claves string y valores int
  2. Agregue las siguientes frutas y cantidades: 
    • "Apple" con una cantidad de 5
    • "Banana" con una cantidad de 10
    • "Orange" con una cantidad de 7
  3. Devuelva el Dictionary creado

Hoja de referencia

En C#, un Dictionary almacena pares clave-valor para una búsqueda eficiente:

Crear un Dictionary vacío:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>();

Agregar elementos a un Dictionary:

fruitInventory.Add("Apple", 10);
fruitInventory.Add("Banana", 15);

Inicializar un Dictionary con valores:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>()
{
    { "Apple", 10 },
    { "Banana", 15 }
};

Pruébalo tú mismo

using System;
using System.Collections.Generic;

class Program
{
    public static Dictionary<string, int> CreateFruitInventory()
    {
        // Escribe tu código aquí
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = CreateFruitInventory();
        
        // Mostrar el inventario
        foreach (var item in inventory)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}
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