型指定したキーと値のペアを作成する
型指定したキーと値のペアを作成する
Dictionaryジェンリッククラスを使用することで型指定したキーと値のペアを作成することが出来ます。
new Dictionary<キーの型, 値の型>
Dictionaryを使用して作成したコレクションは型指定を行っているためHashTableで作成したコレクションより高速に処理されます。
Dictionaryオブジェクトへのキーの追加はHashTable同様、キーを指定して値を代入するか、Addメソッドを使用して追加します。
Dictionary[キー] = 値
Dictionary.Add(キー,値);
すでにコレクション内に同一のキーが存在する場合ArgumentExceptionの例外が発生します。
要素を取り除く方法もまたHashTable同様Removeメソッドを使用して要素を取り除きます。
Dictionary.Remove(キー);
private void button1_Click(object sender, EventArgs e) { Dictionary<string, string> hashA = new Dictionary<string, string>(); hashA["A1"] = "B1"; hashA["A2"] = "B2"; foreach (string key in hashA.Keys) { MessageBox.Show(key + " " + hashA[key]); } hashA.Remove("A1"); foreach (string key in hashA.Keys) { MessageBox.Show(key + " " + hashA[key]); } Dictionary<string, string> hashB = new Dictionary<string, string>(); hashB.Add("C1", "D1"); hashB.Add("C2", "D2"); foreach (string key in hashB.Keys) { MessageBox.Show(key + " " + hashB[key]); } hashB.Remove("C2"); foreach (string key in hashB.Keys) { MessageBox.Show(key + " " + hashB[key]); } }