FC2ブログ
    04 «1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.» 06

    ハルシオンシステムの気ままBlog

    株式会社ハルシオンシステムのメンバーが送る、UnityやらJavaやらの技術的話題から、自社開発のアプリの宣伝とかとかのブログです。ほんと気ままにいきたいと思います。更新日は毎週 月 木でっす!

     

    【ハルシオンブログ】Unity(C#)でDictionaryの紹介。Listばっかり使ってたけどこいつも悪くはねえなぁ 

    こんにちは!坂内っす。

    雨すごいらしいっすね・・・・九州は川も氾濫危険水位に達しているようで・・・・
    皆さんお気をつけてくださいませ。

    UnityというかC#でDictionaryって使ってます?

    ListとかArrayとか配列とかと同じ感じで使えるやつです。
    連想配列って言われるらしいです。

    使うには、usingが必要になります。


    using System.Collections.Generic;


    Listとかとの違いは、添え字の代わりに任意のデータ型を使います。

    ・Listとか

    List<int> intAry = new List<Int>();
    intAry.Add(1);
    intAry.Add(3);
    intAry.Add(5);
    intAry.Add(7);

    Debug.Log(intAry[2]);


    結果は「5」が取れますよね。
    この時intAry[2] という感じに、"3番目"に入っている値という感じで、添え字を使うと思います。

    これがDictionaryだとこんな感じになります。

    ・Dictionaryの場合

    Dictionary<string, int> dic = new Dictionary<string, int>();
    dic.Add("no1", 1);
    dic.Add("no2", 3);
    dic.Add("no3", 5);
    dic.Add("no4", 7);

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


    これも結果は「3」が取れます。

    こんな感じで、文字列など(key)でvalueをとる感じになります。

    また、keyは同じものを入れることができません。


    Dictionary<string, int> dic = new Dictionary<string, int>();
    dic.Add("no1", 1);
    dic.Add("no2", 3);
    dic.Add("no2", 5);


    こういうことができないということです。

    ちなみに初期化時に値を入れる場合はこんな感じでできます。


    Dictionary<string, int> dic = new Dictionary<string, int>()
    {
    {"no1", 1},
    {"no2", 3},
    {"no3", 5}
    }


    valueの更新はこんな感じ。


    Dictionary<string, int> dic = new Dictionary<string, int>()
    {
    {"no1", 1},
    {"no2", 3},
    {"no3", 5}
    }

    dic["no2"] = 100;


    特定のkeyがあるかどうかは、こんな感じで判定できます。


    Dictionary<string, int> dic = new Dictionary<string, int>()
    {
    {"no1", 1},
    {"no2", 3},
    {"no3", 5}
    }

    if(dic.ContainsKey("no2")){
    Debug.Log("no2があるので更新");
    dic["no2"] = 50;
    } else {
    Debug.Log("no2がないので追加");
    dic,Add("no2", 50);
    }


    また、全体をなめる感じの場合は、foreachでいけますね。


    Dictionary<string, int> dic = new Dictionary<string, int>()
    {
    {"no1", 1},
    {"no2", 3},
    {"no3", 5}
    }

    foreach(Dictionary<string, int> data in dic){
    Debug.Log(data.key + ":" + data.value);
    }


    こんな感じで、全部をとることができます。
    Dictionaryでは順不動のようで、上記のように全部をなめる時に順番が変わる可能性があるらしいです。

    登録した順番に何かの処理をする必要がある場合は、DictionaryではなくList等を使わないといけません。

    という感じで、Dictionaryの紹介でした。

    では、あでゅ~ノシ

    Category: 開発日記(Unity)

    tb 0 : cm 0   

    コメント

    コメントの投稿

    Secret

    トラックバック

    トラックバックURL
    →http://halcyonsystemblog.jp/tb.php/715-cb8aa49e
    この記事にトラックバックする(FC2ブログユーザー)