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チャレンジ
中級Dictionary<string, int> を引数として受け取り、以下の操作を実行する ProcessDictionary という名前のメソッドを作成してください。
Keys:と出力し、続けてすべてのキーを出力します(1行に1つずつ)。Values:と出力し、続けてすべての値を出力します(1行に1つずつ)。- ディクショナリに
"total"というキーが含まれているか確認し、Contains 'total': TrueまたはContains 'total': Falseと出力します。 "temp"というキーが存在する場合は削除します。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}");
}
}
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
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 Safety