HashMap Methods
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 proporcionan formas potentes de trabajar con tus datos de diccionario. Exploremos algunos métodos comunes:
Comprobar 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 will be trueObtener todas las claves del diccionario:
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);
// Get all keys
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
Console.WriteLine(name);
}Obtener todos los valores del diccionario:
// Get all values
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
Console.WriteLine(score);
}Eliminar un elemento del diccionario:
scores.Remove("Bob");
// Dictionary now only contains Alice's scoreLimpiar todos los elementos:
scores.Clear();
// Dictionary is now emptyObtén el número de elementos en el 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);
// Output: 2Desafío
IntermedioCrea un método llamado ProcessDictionary que tome un Dictionary<string, int> como argumento y realice las siguientes operaciones:
- Imprime
Keys:seguido de todas las claves (una por línea) - Imprime
Values:seguido de todos los valores (una por línea) - Verifica si el diccionario contiene la clave
"total"e imprimeContains 'total': TrueoContains 'total': False - Elimina la clave
"temp"si existe - Imprime
Count:seguido del conteo de elementos en el diccionario después de estas operaciones (usa la propiedad.Countdel diccionario)
Hoja de referencia
Verifica si una clave existe usando ContainsKey():
bool hasKey = dictionary.ContainsKey("keyName");Obtén todas las claves de un diccionario:
Dictionary<string, int>.KeyCollection keys = dictionary.Keys;
foreach (string key in keys)
{
Console.WriteLine(key);
}Obtén todos los valores de un diccionario:
Dictionary<string, int>.ValueCollection values = dictionary.Values;
foreach (int value in values)
{
Console.WriteLine(value);
}Elimina un elemento usando Remove():
dictionary.Remove("keyName");Limpia todos los elementos usando Clear():
dictionary.Clear();Obtén el número de elementos usando .Count:
int count = dictionary.Count;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 string a un HashMap
static void Main(string[] args)
{
Dictionary<string, int> inputDict = 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
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);
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}");
}
}
}
}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
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 Safety