Menu
CoddyTech

HashMap のメソッド

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");
// Dictionary には現在 Alice のスコアだけが含まれています

Remove() は、キーが存在して削除された場合は true を返し、存在しなかった場合は false を返します。存在しないキーを削除してもエラーにはなりません。

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

scores.Clear();
// Dictionary は空になりました

.Countを使って、辞書内の項目数を取得します。

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

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

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

自分で練習してみよう: C#オンラインコンパイラ