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チャレンジ
中級ProcessDictionary という名前のメソッドを作成し、Dictionary<string, int> を引数として受け取り、次の操作を実行してください:
Keys:に続いてすべてのキー(1行に1つ)を印刷しますValues:に続いてすべての値(1行に1つ)を印刷します- 辞書にキー
"total"が含まれているかどうかをチェックし、Contains 'total': TrueまたはContains 'total': Falseを印刷します - 存在する場合はキー
"temp"を削除します - これらの操作の後、辞書内のアイテム数を
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}");
}
}
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
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