Menu
Coddy logo textTech

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");

上記のコードを実行した後、変数 existstrue になります。

これを条件分岐文で使用できます:

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 icon

チャレンジ

簡単

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);
        }
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン