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 will be 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);
}

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

// Get all values
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
    Console.WriteLine(score);
}

辞書から項目を削除:

scores.Remove("Bob");
// Dictionary now only contains Alice's score

すべての項目をクリア:

scores.Clear();
// Dictionary is now empty

辞書の要素数を .Count を使用して取得します:

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

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

チャレンジ

中級

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

  1. Keys: に続いてすべてのキー(1行に1つ)を印刷します
  2. Values: に続いてすべての値(1行に1つ)を印刷します
  3. 辞書にキー "total" が含まれているかどうかをチェックし、Contains 'total': True または Contains 'total': False を印刷します
  4. 存在する場合はキー "temp" を削除します
  5. これらの操作の後、辞書内のアイテム数を Count: に続いて印刷します(辞書の .Count プロパティを使用)

チートシート

ContainsKey() を使用してキーの存在を確認:

bool hasKey = dictionary.ContainsKey("keyName");

辞書からすべてのキーを取得:

Dictionary<string, int>.KeyCollection keys = dictionary.Keys;
foreach (string key in keys)
{
    Console.WriteLine(key);
}

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

Dictionary<string, int>.ValueCollection values = dictionary.Values;
foreach (int value in values)
{
    Console.WriteLine(value);
}

Remove() を使用して項目を削除:

dictionary.Remove("keyName");

Clear() を使用してすべての項目をクリア:

dictionary.Clear();

.Count を使用して項目の数を確認:

int count = dictionary.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>();
        
        // Read first line to check if it's JSON 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);
                        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腕試し

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

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