1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

 今回は、データをまとめて扱うのに便利なListの使い方と、Listとfor文を併用したループ処理について解説していきます。

この記事の目標

  • Listの宣言方法と要素へのアクセス方法を理解する
  • Listへの要素の追加(Add)・削除(Remove)ができる
  • for文を使ってListの全要素を処理できる

Listの使い方

 Listは、同じ型の値をまとめて取り扱うためのクラスで、以下のように宣言します。

using System.Collections.Generic; // C#でListを使うために必要

List<int> list = new List<int>(); // int型を格納するListを宣言

List<int> num = new List<int>() // 宣言時に初期値も指定できる
{
	1, 2, 3, 4, 5
};

List<string> shikoku = new List<string>() // string型を格納するListを宣言
{
	"ehime", "kagawa", "kouchi", "tokushima" // ""で囲む
};

 Listの要素は0番から始まり、各要素には以下のようにアクセスすることができます。

int n = num[2]; // numのうち、0から数えて2番目の要素の3がnに入る

Listの要素の追加と削除

 要素の追加はAdd、削除はRemoveを用いて以下のように行います。

List<string> list = new List<string>();

list.Add("hello"); // 末尾の0番に追加
list.Add("bye"); // 末尾の1番に追加
list.Add("hello"); // 末尾の2番に追加

list.Remove("bye"); // "bye"が格納された1番を削除、以降の番号は前に詰められる
list.Remove("hello"); // "hello"が格納されている物のうち一番先頭の0番を削除、以降の番号は前に詰められる

Listとfor文の併用

 for文を用いることで、簡単にListのそれぞれの要素に処理を加える事が可能です。

List<int> num = new List<int>();

// numに数値を追加する処理

// 全ての要素を2乗する処理
for(int i = 0; i < num.Count; i++) // .Countを用いてnumの要素数を取得
{
	num[i] *= num[i];
}

// 前から偶数番目の要素を0にする処理
for(int i = 1; i < num.Count; i += 2) // .Countを用いてnumの要素数を取得
{
	num[i] = 0;
}

まとめ

 今回はListの宣言と要素の追加と削除、for文との併用について解説していきました。ゲーム開発のように、いくつもの変数を管理する場面で便利ですので、ぜひ覚えて使ってみてください。

お疲れ様でした。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?