C#で連想配列を使う方法(Dictionaryクラス)
C#で連想配列を使う場合はDictionaryクラスを使います。
連想配列はデータを扱う上で便利なので押さえておきましょう。
[ad#top-1]
基本形
//using System.Collections.Generic;
Dictionary<string, int> dic = new Dictionary<string, int>();
dic["山田太郎"] = 51;
dic["鈴木一郎"] = 38;
dic["池田隆"] = 42;
dic["佐藤正"] = 28;
dic["渡辺博"] = 57;
dic.Add("田中剛", 10);
Addメソッドは上書き不可
//すでに山田太郎というキーが存在するとして
//上書きOK
dic["山田太郎"] = 49;
//例外発生
dic.Add("山田太郎", 49);
キーの存在確認
bool b = dic.ContainsKey("鈴木一郎");
if(b) MessageBox.Show("OK");
繰り返し処理
foreach(string s in keys){
MessageBox.Show(s);
}
キーまたは値をListに変換する
List<string> keys = new List<string>(dic.Keys); List<int> values = new List<int>(dic.Values);
[ad#ad-1]
スポンサーリンク