HashMap Methods
Part of the Logic & Flow section of Coddy's C# journey — lesson 52 of 66.
HashMap methods provide powerful ways to work with your dictionary data. Let's explore some common methods:
Check if a key exists in the dictionary:
Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);
bool hasApples = inventory.ContainsKey("apples");
// hasApples will be trueGet all keys from the dictionary:
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);
}Get all values from the dictionary:
// Get all values
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
Console.WriteLine(score);
}Remove an item from the dictionary:
scores.Remove("Bob");
// Dictionary now only contains Alice's scoreClear all items:
scores.Clear();
// Dictionary is now emptyGet the number of items in the dictionary using .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: 2Challenge
MediumCreate a method named ProcessDictionary that takes a Dictionary<string, int> as an argument and performs the following operations:
- Print
Keys:followed by all keys (one per line) - Print
Values:followed by all values (one per line) - Check if the dictionary contains the key
"total"and printContains 'total': TrueorContains 'total': False - Remove the key
"temp"if it exists - Print
Count:followed by the count of items in the dictionary after these operations (use the.Countproperty of the dictionary)
Cheat sheet
Check if a key exists using ContainsKey():
bool hasKey = dictionary.ContainsKey("keyName");Get all keys from a dictionary:
Dictionary<string, int>.KeyCollection keys = dictionary.Keys;
foreach (string key in keys)
{
Console.WriteLine(key);
}Get all values from a dictionary:
Dictionary<string, int>.ValueCollection values = dictionary.Values;
foreach (int value in values)
{
Console.WriteLine(value);
}Remove an item using Remove():
dictionary.Remove("keyName");Clear all items using Clear():
dictionary.Clear();Get the number of items using .Count:
int count = dictionary.Count;Try it yourself
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
static void ProcessDictionary(Dictionary<string, int> dict)
{
// Write your code here
}
// Ignore the main code, it converts string to a 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}");
}
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
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