C#•辞書
C# Dictionary<TKey, TValue>:ハッシュテーブル操作
C# での高速ハッシュ検索と TryGetValue を使った安全な取得パターンを学びます。
構文
var dict = new Dictionary<string, int>();
dict["key"] = 100;
dict.TryGetValue("key", out int val);
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| TryGetValue | Method | KeyNotFoundException をスローせずに安全に値を取得します。 |
そのまま実行できるコード例
Compilra で実行可能C# をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
var portRegistry = new Dictionary<string, int> {
["HTTP"] = 80,
["HTTPS"] = 443,
["SSH"] = 22
};
// Adding entries
portRegistry["REDIS"] = 6379;
// Safe lookup with TryGetValue
string queryProtocol = "HTTPS";
if (portRegistry.TryGetValue(queryProtocol, out int port)) {
Console.WriteLine($"{queryProtocol} is bound to port {port}");
}
Console.WriteLine("\nAll Registered Ports:");
foreach (var kvp in portRegistry) {
Console.WriteLine($" {kvp.Key} -> {kvp.Value}");
}
}
}期待される出力:
HTTPS is bound to port 443 All Registered Ports: HTTP -> 80 HTTPS -> 443 SSH -> 22 REDIS -> 6379
動作のしくみ: ステップ解説
- 6-10 行目: C# インデクサー初期化構文で Dictionary を初期化します。
- 17-19 行目: TryGetValue が例外を投げずに安全にポートを取得します。
重要ポイント
- Dictionary は検索と挿入を平均 O(1) で行えます。
- dict[missingKey] へのアクセスは KeyNotFoundException を投げるため、TryGetValue または ContainsKey を使ってください。
よくある間違い: 存在しないキーをインデクサー dict[missingKey] で読み取る
未登録キーを読むと KeyNotFoundException がスローされます。代わりに TryGetValue を使用してください。
❌ 誤り
int p = portRegistry["UNKNOWN"]; // Throws KeyNotFoundException!
✅ 正しい例
portRegistry.TryGetValue("UNKNOWN", out int p); // Safe