LoginSignup
35
38

More than 5 years have passed since last update.

Unity C#のコレクションってなんぞや 〜もっと自由に配列扱いたくて〜

Last updated at Posted at 2015-11-08

UnityでC#書いてて
普段主にjsを書いている私はC#の配列操作が謎で困りました。
(サイズの決まってない配列の扱いとか、、json受け取るとき何で受け取ればいいんだとか)
そんな時出会ったのが噂の「コレクション」です。

壮大なイメージでしたが、
「用途によって使い分けてね、便利なオブジェクトの管理用の拡張配列クラスこれくしょんしたよ」
って感じでした。

C#では、多数のオブジェクトをまとめて扱う場合、
配列の他に「コレクション」と呼ばれるクラスを利用することができます。
コレクションは、 System.Collection.Genericsというパッケージにまとめられています。

▫️参考
http://libro.tuyano.com/index3?id=2656003

ArrayList
List
Hashtable
Dictionary
Queue (怖いので今回触れない)
Stack (怖いので今回触れない)
などがあるそうです。

ArrayList

オブジェクトを順番付けして管理するためのコレクションです。
平たくいえば、「配列とだいたい同じような扱い方ができるコレクション」

hoge
using System;
using System.Collection.Generics; // これ忘れず

ArrayList list = new ArrayList();
list.Add("hoge");
list.Remove("hoge");
list[0] =  "hoge";
int num = list.Count;   // 要素数

List

ArrayListとだいたい同じ
決まった種類のオブジェクトだけを保管しておくような場合
ArrayListと同じメソッドが用意されてる

hoge
using System;
using System.Collections.Generic; // さっきと変わりました、ジェネリックです

List<string> list = new List<string>();
list.Add("One");  // とか一緒

// おまけのforeach
foreach(String str in list){
    Debug.Log(str);
}

Hashtable

一般に「連想配列」とか「ハッシュ」とかいわれるもの。
インデックス番号を使わずにキーでオブジェクトを管理。

hoge
using System;
using System.Collection.Generics;

Hashtable table = new Hashtable();
table.Add("tom","tom@hogehoge.com");
table["tom"] = "tom@hogehoge.com";
table.Remove("tom");

Dictionary

ArrayListに決まった種類のオブジェクト版のListがあるように、
このHashtableにもあり、それがDictionary。
Dictionary < クラス名 , クラス名> 変数 = new Dictionary < クラス名 , クラス名 >();
使い方は基本的にHashtableと同じ

hoge

using System;
using System.Collections.Generic;

Dictionary<string,string> dict = new Dictionary<string, string>();
dict.Add("tom","tom@hogehoge.com");
dict["tom"] = "tom@hogehoge.com";
dict.Remove("tom");
35
38
2

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
35
38