Check If Key Exists
Part of the Logic & Flow section of Coddy's C# journey — lesson 48 of 66.
To check if a key exists in a HashMap (Dictionary in C#), you can use the ContainsKey() method.
First, create a Dictionary:
Dictionary<string, int> ages = new Dictionary<string, int>();Add some key-value pairs:
ages.Add("John", 25);
ages.Add("Mary", 30);Now check if a key exists:
bool exists = ages.ContainsKey("John");After executing the above code, the variable exists will be true.
You can use this in a conditional statement:
if (ages.ContainsKey("John"))
{
Console.WriteLine("John's age is in the dictionary");
}
else
{
Console.WriteLine("John's age is not in the dictionary");
}Challenge
EasyCreate a method named CheckKeyExists that takes two arguments:
- A Dictionary<string, int> (dictionary)
- A string (key) to check
The method should check if the key exists in the dictionary and print:
- "Key exists" if the key is found
- "Key does not exist" if the key is not found
Cheat sheet
To check if a key exists in a Dictionary, use the ContainsKey() method:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Mary", 30);
bool exists = ages.ContainsKey("John"); // returns trueUse in conditional statements:
if (ages.ContainsKey("John"))
{
Console.WriteLine("John's age is in the dictionary");
}
else
{
Console.WriteLine("John's age is not in the dictionary");
}Try it yourself
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
{
// Write code here
}
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
// Reading inventory input - accepts both JSON format and line-by-line 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);
inventory.Add(keyMatch, valueMatch);
}
}
// Reading the key to check directly
string keyToCheck = Console.ReadLine();
CheckKeyExists(inventory, keyToCheck);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
else
{
// Process original line-by-line format
string line = firstLine;
// Read lines until an empty line is entered
while (!string.IsNullOrEmpty(line))
{
try
{
string[] parts = line.Split(':');
if (parts.Length == 2)
{
inventory.Add(parts[0], int.Parse(parts[1]));
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing line: {ex.Message}");
}
// Read next line
line = Console.ReadLine();
}
// Reading the key to check
string keyToCheck = Console.ReadLine();
CheckKeyExists(inventory, keyToCheck);
}
}
}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 Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap