Menu
Coddy logo textTech

HashMap Methods

CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 52/66。

HashMapのメソッドは、辞書データを操作するための強力な方法を提供します。いくつかの一般的なメソッドを見ていきましょう。

辞書内にキーが存在するかどうかを確認します:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);

bool hasApples = inventory.ContainsKey("apples");
// hasApples は true になります

ディクショナリからすべてのキーを取得します:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

// すべてのキーを取得
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
    Console.WriteLine(name);
}

辞書からすべての値を取得します:

// すべての値を取得
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
    Console.WriteLine(score);
}

ディクショナリから項目を削除します:

scores.Remove("Bob");
// ディクショナリには Alice のスコアのみが含まれるようになりました

すべての項目をクリアする:

scores.Clear();
// ディクショナリは空になりました

.Countを使用して、Dictionary内の要素数を取得します:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

int total = scores.Count;
Console.WriteLine(total);
// 出力: 2
challenge icon

チャレンジ

中級

Dictionary<string, int> を引数として受け取り、以下の操作を実行する ProcessDictionary という名前のメソッドを作成してください。

  1. Keys: と出力し、続けてすべてのキーを出力します(1行に1つずつ)。
  2. Values: と出力し、続けてすべての値を出力します(1行に1つずつ)。
  3. ディクショナリに "total" というキーが含まれているか確認し、Contains 'total': True または Contains 'total': False と出力します。
  4. "temp" というキーが存在する場合は削除します。
  5. Count: と出力し、続けてこれらの操作を行った後のディクショナリ内のアイテム数を出力します(ディクショナリの .Count プロパティを使用してください)。

自分で試してみよう

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    static void ProcessDictionary(Dictionary<string, int> dict)
    {
        // ここにコードを記述してください
    }
    // メインコードは無視してください。文字列を `HashMap` に変換します
    static void Main(string[] args)
    {
        Dictionary<string, int> inputDict = 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);
                        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}");
            }
        }
    }
}
quiz icon腕試し

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

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