C#
SortedDictionary を選ぶ場面 (キー順序が必要な時)
出典: C# Dictionary と HashTable の使い分け — 業務SEが型安全に書く3つの判断軸 — SortedDictionary を選ぶ場面 (キー順序が必要な時)
// 設定キーをアルファベット順で反復したい場面
SortedDictionary<string, string> config = new SortedDictionary<string, string>();
config.Add("zebra", "ZZ");
config.Add("apple", "AA");
config.Add("mango", "MM");
foreach (var kv in config) {
Console.WriteLine($"{kv.Key}={kv.Value}");
// 出力: apple=AA, mango=MM, zebra=ZZ (キー昇順)
}
▸ 実行ボタンで結果を表示
Source収録記事
この snippet は記事の「SortedDictionary を選ぶ場面 (キー順序が必要な時)」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
4 件// Dictionary なら自然に書ける var highScores = scores.Where(kv => kv.Value >= 90).ToList(); // HashTable だと…未収録
LINQ が使えるかどうかも判断軸 (HashTable は使えない)
#9612fbf51551
// int キー: HashTable では毎回 boxing → GetHashCode 呼び出し Hashtable ht = new Hashtable(); ht.Add(42, "answer"); var v1 = ht[42]; // 42 → object に boxing → GetHashCode → バケット検索未収録
ハマり② int キーと string キーで Equals/GetHashCode 挙動が違う
#c23d4bac8db3
// 注文ID + 行番号 を複合キーにしたい例 public struct OrderLineKey { public int OrderId;未収録
カスタム型 (struct / class) をキーにする時の落とし穴
#fa8cecd1df36
public struct OrderLineKey : IEquatable<OrderLineKey> { public int OrderId; public int LineNo;未収録
カスタム型 (struct / class) をキーにする時の落とし穴
#b7c4e6e892b5
