値にアクセスする
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部。レッスン 49/66。
C#では、HashMapに相当するものとしてDictionary<TKey, TValue>を使います。Dictionaryに項目を追加した後、それらを取得する必要があります。
string型のキーとint型の値を持つDictionaryを作成しましょう。
Dictionary<string, int> studentScores = new Dictionary<string, int>();いくつか項目を追加しましょう。
studentScores.Add("John", 95);
studentScores.Add("Mary", 88);キーを使って値にアクセスする:
int johnScore = studentScores["John"];上記のコードを実行すると、johnScore には次の値が格納されます。
95注意してください!存在しないキーにアクセスしようとすると、KeyNotFoundException が発生します。
// "Bob" が dictionary に存在しない場合、例外がスローされます
int bobScore = studentScores["Bob"];チャレンジ
簡単GetValueByKeyという名前のメソッドを作成します。このメソッドは2つの引数を受け取ります。
- Dictionary<string, int>(辞書)。
- 検索するstring(キー)。
このメソッドでは、指定されたキーの値へのアクセスを試み、次のようにします。
- キーが存在する場合は、その値を出力します。
- キーが存在しない場合は、"Key not found"を出力します。
自分で試してみよう
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void GetValueByKey(Dictionary<string, int> dictionary, string key)
{
// ここにコードを書く
}
static void Main(string[] args)
{
// JSON形式の辞書を読み込む: {"key1":value1,"key2":value2}
string dictionaryInput = Console.ReadLine();
string key = Console.ReadLine();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// 入力文字列を解析して辞書を作成する
if (!string.IsNullOrEmpty(dictionaryInput))
{
try
{
// 入力がJSON形式かどうかを確認する
if (dictionaryInput.StartsWith("{") && dictionaryInput.EndsWith("}"))
{
// 波括弧を取り除く
string jsonContent = dictionaryInput.Substring(1, dictionaryInput.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);
dictionary.Add(keyMatch, valueMatch);
}
}
}
// Handle the original format "key1:value1,key2:value2" as fallback
else
{
string[] pairs = dictionaryInput.Split(',');
foreach (string pair in pairs)
{
string[] keyValue = pair.Split(':');
if (keyValue.Length == 2)
{
dictionary.Add(keyValue[0], int.Parse(keyValue[1]));
}
}
}
GetValueByKey(dictionary, key);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ