Dictionaryの使い方
System.Collections.Generic を読み込む。
using System.Collections.Generic;
Dictionaryを初期化する
string 型のキーと string 型の要素のディクショナリー
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string 型のキーと int 型の要素のディクショナリー
Dictionary<string, int> dictionary = new Dictionary<string, int>();
初期値を設定する
Dictionary<string, int> dictionary = new Dictionary<string, int>() {
{ "key0", 10 },
{ "key1", 100 }
};
要素を追加する
key2 というキーで 1000 の要素を追加する。
dictionary.Add("key2", 1000);
下記の方法でも追加が可能です。また、キーが存在する場合には上書きします。
dictionary["key2"] = 2000;
要素を取得する
key0 と名付けた要素を取得する
dictionary["key0"];
要素を削除する
key0 と名付けた要素を削除する
dictionary.Remove ("key0");
Dictionaryのキーを列挙する
.Keys で列挙できます。key の型が初期化時と同じである必要があります。
foreach (string key in dictionary.Keys) {
print (key);
}
Dictionaryの要素を列挙する
.Values で列挙できます。value の型が初期化時と同じである必要があります。
foreach (int value in dictionary.Values) {
print (value);
}
Dictionaryのキーと要素を列挙する
KeyValuePairで列挙できます。
foreach (KeyValuePair<string, int> item in dictionary) {
print(item.Key + " : " + item.Value);
}
要素の数を取得する
print (dictionary.Count);
指定されたキーが存在するか調べる
true か false で返ってきます。
dictionary.ContainsKey( "key3" )