Accessing Values
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 49/66。
C# では、HashMap の同等として Dictionary<TKey, TValue> を使用します。Dictionary に項目を追加した後、それらを取得する必要があります。
文字列のキーと 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" が辞書に存在しない場合、例外が発生します
int bobScore = studentScores["Bob"];チャレンジ
簡単GetValueByKey という名前のメソッドを作成し、2つの引数を受け取ります:
- Dictionary<string, int> (辞書)。
- 検索する string (キー)。
このメソッドは、指定されたキーの値にアクセスしようとし、
- キーが存在する場合、値を印刷します。
- キーが存在しない場合、"Key not found" を印刷します。
チートシート
文字列キーとint値を持つDictionaryを作成:
Dictionary<string, int> studentScores = new Dictionary<string, int>();Dictionaryにエントリを追加:
studentScores.Add("John", 95);
studentScores.Add("Mary", 88);キーを使用して値にアクセス:
int johnScore = studentScores["John"];存在しないキーにアクセスするとKeyNotFoundExceptionがスローされます:
// "Bob" が辞書にない場合、例外がスローされます
int bobScore = studentScores["Bob"];自分で試してみよう
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}");
}
}
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap