C# - リスト(List)の初期化方法

空のリストを作成するには new List<データ型>()、値を指定して初期化するには { } 内に初期値を指定します。

リスト(List)の初期化方法

空のリスト
using System.Collections.Generic;

List<データ型> 変数名 = new List<データ型>();

初期値を指定

using System.Collections.Generic;

List<データ型> 変数名 = new List<データ型>() { 0番目の値, 1番目の値 };

サンプルコード

サンプルコード1 - 初期値を設定してリストの初期化
using System.Collections.Generic;

// 文字列(string)のリストを作成
List<string> stringList = new List<string>() { "文字列0", "文字列1", "文字列2" };

// 数値(int)のリストを作成
List<int> intList = new List<int>() { 0, 1, 2 };

サンプルコード2 - 空のリストを作成し、add メソッドで 値を追加

using System.Collections.Generic;

// 空の文字列リストを作成
List<string> stringList = new List<string>();

// 文字列リストに値を追加
stringList.Add("文字列0");
stringList.Add("文字列1");
stringList.Add("文字列2");


// 空の数値リストを作成
List<int> intList = new List<int>();

// 数値リストに値を追加
intList.Add(0);
intList.Add(1);
intList.Add(2);

サンプルコード1 と サンプルコード2 の結果は 同じ です サンプルコード1の実行結果 サンプルコード2の実行結果

配列の初期化方法

配列の初期化方法は次の記事を参照してください。

検証環境

関連ページ