LoginSignup
70
56

More than 5 years have passed since last update.

C#のDictionary【Unity, C#】

Last updated at Posted at 2015-07-29

C#でDictionaryを使用したので、メモ。

名前空間

using System.Collections.Generic;

宣言

Dictionary<GameObject, Vector3> temp;

コンストラクタ

Dictionary<string, string> dic = new Dictionary<string, string> ();

初期値を設定する場合

Dictionary<string, string> dic = new Dictionary<string, string> () {
        {"key0", "value0"},
        {"key1", "value1"}
    };

要素の追加

dic.Add ("key2", "value2");
dic.Add ("key3", "value3");

要素の取り出し

Debug.Log (dic ["key0"]);

キーの列挙

foreach (string key in dic.Keys) {
    Debug.Log (key);
}

要素の列挙

foreach (string value in dic.Values) {
    Debug.Log (value);
}

キーと要素の列挙

foreach (KeyValuePair<string, string> pair in dic) {
    Debug.Log (pair.Key + " : " + pair.Value);
}

要素数

Debug.Log (dic.Count);

要素列挙の順番

Addの順番通りに出力されます。
※このサンプルがたまたまAddと同じ順番で出力されているだけなのかもしれません。

Dictionary<string, string> temp = new Dictionary<string, string> ();
for (int i = 0; i < 10; i++) {
    temp.Add ("key" + i.ToString(), "value" + i.ToString());
}

foreach (KeyValuePair<string, string> pair in temp) {
    Debug.Log(pair.Key + " : " + pair.Value);
}

結果
スクリーンショット 2015-08-04 14.25.37.png

要素の削除

dic.Remove ("key0");
70
56
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
70
56