LoginSignup
0
0

【C#】配列の初期化

Posted at

概要

C#での配列(一部List)の初期化方法や要素アクセス等に関するメモ書き
出来るだけ分かりやすい方法

0. newでのデフォルト値による方法

"new 型[要素数]"で空の配列を作成すると
オブジェクト型 → デフォルト値に変数が初期化される

test.cs
int[] array1 = new int[5];
float[,] array2 = new float[3,8];

// これはエラー.初期化時に要素数を指定する必要がある.
int[] array3 = new int[]; // CS1586
float[,] array4 = new float[,]; // CS1586

1. 要素を代入する方法 (手書き)

// 1次元配列
int[] array1 = new int[] { 2, 4, 6, 8, 10, };
// 2次元配列
int[,] array2 = new int[,] { { 1, 2 },{ 3, 4 },{ 5, 6 }, };

// new式と型は省略可能 .
int[] array3 = { 2, 4, 6, 8, 10 };

2. for文で回す方法 (力技)

初心者にも分かりやすく代入値も簡単に編集可能だが,いちいちfor文を書くのはめんどくさい

int[] array = new int[5];
for(i=0; i<intArray.Length; ++i) {
    array[i] = 1; // 同じ値で初期化
    array[i] = i; // 連続した値で初期化
}

3. LINQによる方法

int[] array1 = Enumerable.Repeat(1,5).ToArray(); // 同じ値で初期化
int[] array2 = Enumerable.Range(1,5).ToArray();  // 連続した値で初期化

float[] array3 = Enumerable.Range(1,5)
                .Select(x => x*0.1f)  // 任意の値に変更
                .ToArray();
0
0
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
0
0