Check If Key Exists
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 48/66。
HashMap(C# の Dictionary)でキーが存在するかどうかを確認するには、ContainsKey() メソッドを使用できます。
まず、Dictionaryを作成します:
Dictionary<string, int> ages = new Dictionary<string, int>();いくつかのキー-値ペアを追加:
ages.Add("John", 25);
ages.Add("Mary", 30);次に、キーが存在するかどうかを確認します:
bool exists = ages.ContainsKey("John");上記のコードを実行した後、変数 exists は true になります。
これを条件分岐文で使用できます:
if (ages.ContainsKey("John"))
{
Console.WriteLine("John's age is in the dictionary");
}
else
{
Console.WriteLine("John's age is not in the dictionary");
}チャレンジ
簡単CheckKeyExists という名前のメソッドを作成し、2 つの引数を受け取る:
- Dictionary<string, int> (dictionary)
- チェックする string (key)
このメソッドは、辞書にキーが存在するかどうかをチェックし、以下を出力します:
- キーが見つかった場合 "Key exists"
- キーが見つからない場合 "Key does not exist"
チートシート
Dictionary でキーが存在するかどうかを確認するには、ContainsKey() メソッドを使用します:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Mary", 30);
bool exists = ages.ContainsKey("John"); // returns true条件分岐文で使用:
if (ages.ContainsKey("John"))
{
Console.WriteLine("John's age is in the dictionary");
}
else
{
Console.WriteLine("John's age is not in the dictionary");
}自分で試してみよう
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
{
// ここにコードを記述してください
}
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
// 在庫入力を読み取ります - JSON形式と行ごとの形式の両方を受け入れます
string firstLine = Console.ReadLine();
// 入力がJSON形式かどうかを確認します
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// JSON入力を処理します
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// 引用符の中にないカンマで分割します
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// 正規表現を使用してキーと値を抽出します
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);
}
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
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