LoginSignup
0
0

More than 1 year has passed since last update.

配列処理を明確にする(for, foreach, while)

Posted at

はじめに

以前にも、配列処理についてはまとめましたが、まだ具体的に理解できていなかったのと少し時間が経ったので改めてまとめたいと思います。
今回は配列からデータを取得する方法に観点をおいてまとめました。

データを取り出すにはfor / foreach /whileの3種類がある

特徴(使い道)

for
条件が成立するまで繰り返す。
回数が定まっているときに使用。

(頻出)foreach
指定したコレクションから要素を1つずつ取り出してコレクションの要素数分だけ繰り返す。

while
指定の条件を満たすまで繰り返す。
無限ループ注意。

基本構文

for

for(回数を格納する用の変数 = 始まりの値; 繰り返しが続く条件; カウントアップする数)
    {
    //処理内容
    }

foreach

foreach(データ型 変数名 in コレクション)
    {
    //処理内容
    }

while

while(条件式)
    {
     //処理内容
    }

取り出し方(例文)

【for】
配列

string[] protein = {"肉", "魚", "卵"};
void Start()
{
     for(int i = 0; i < protein.Length; i ++)
     {
          Debug.Log(protein[i]);
     }
}

リスト

List<string> protein = new List<string>{"肉", "魚", "卵"};
void Start()
{
     for(int i = 0; i < protein.Count; i ++)
     {
          Debug.Log(protein[i]);
     }
}

【foreach】
配列

string[] protein = {"肉", "魚", "卵"};
void Start()
{
     foreach(string proteinType in protein)
     {
          Debug.Log(proteinType);
     }
}

リスト

List<string> protein = new List<string>{"肉", "魚", "卵"};
void Start()
{
     foreach(string proteinType in protein)
     {
          Debug.Log(proteinType);
     }
}

【while】
配列

string[] protein = {"肉", "魚", "卵"};
void Start()
{
     int i = 0;
     while(i < protein.Length)
     {
          Debug.Log(protein[i]);
          i ++;
     }
}

リスト

List<string> protein = new List<string>{"肉", "魚", "卵"};
void Start()
{
     int i = 0;
     while(i < protein.Count)
     {
          Debug.Log(protein[i]);
          i ++;
     }
}

その他知識

以前に他の記事でコメントをいただいたのですが、
forとforeachでは、 forの方がパフォーマンスは良い とのこと。
また、Listを使う場合、大体はforeach使用する。(またはLinq)
for文は使い道が限定的 である。(コントロールやファイル読み込み等で列挙不可なオブジェクトのlengsをみる必要があるときとか)

関連記事

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