LoginSignup
7
12

More than 3 years have passed since last update.

DictionaryのValue(値)をListにする

Last updated at Posted at 2019-11-21

DictionaryのValue(値)をListにする

DictionaryのKeyをstringに、ValueをListにしたかったので以下のように実装しました。

冷蔵庫に入ってるものを種類別に格納しておくようなものを想定。
Listを定義してからDictionaryにAddするのはコードも長くなるのでなるだけ簡潔に追加したいなと思って以下のようにしました。

ローカル以外では初期化できなかった(UnityだけでなくC#も?)ので、publicとして使いたいものを宣言と同時に初期化で値を入れておくことはできないのかな、と思いこういうコードに。
メソッド内の初期化を忘れており、しばらく
NullReferenceException: Object reference not set to an instance of an object
で怒られました。

宣言と追加

Dictionary_value_list.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Dictionary_value_list : MonoBehaviour
{

    public Dictionary<string,List<string>> MapFridge;

    public void Setmap(){

      //ローカルで初期化
      MapFridge = new Dictionary<string,List<string>>();

      MapFridge.Add("野菜",new List<string>(){"きゅうり","トマト","玉ねぎ"});
      MapFridge.Add("果物",new List<string>(){"みかん","パイナップル","いちご"});
      MapFridge.Add("魚",new List<string>(){"さけ","サバ","はまち"});

    }

}

取得と表示

Dictionary_value_list.cs
      //Keyを取得して表示
      foreach(string s in MapFridge.Keys){
        Debug.Log(s);
      }

コンソールでの表示
key.PNG

Dictionary_value_list.cs
      //Valueを取得して表示
      foreach(List<string> li in MapFridge.Values){
        foreach(string s in li){
            Debug.Log(s);
      }

コンソールでの表示
value.PNG

Dictionary_value_list.cs
      //KeyとValueのPairを取得して表示
      foreach(KeyValuePair<string,List<string>> item in MapFridge){
        Debug.Log(item.Key+"はこれがあります");
        foreach(string s in item.Value){
          Debug.Log(s);
        }
      }

コンソールでの表示
both.PNG

ValueはListなのでさらにその中の要素に対してforeach。
Debug.Logはデフォルトで改行されちゃうので、同一行に出力したいときにfor文とか回してしまうと必ず改行されちゃうのが不便。
どうしても改行したくないときは、stringに連結していって最後に表示するとか。

一要素だけ取り出すときにはKeyを指定するしかなさそう。

7
12
1

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
7
12