プログラミングを試してみたい人向けのC#プログラミングチュートリアル

分岐と繰返し

POINT
  • データの塊として使用する代表的な方法は配列とList
  • 配列の使い方を学ぶ
  • Listの使い方を学ぶ
目次

データをまとめて扱うことができる配列

配列はエクセルのようにデータをズラッと並べて管理できるような変数です。
データをまとめられるため繰返しでの処理がしやすかったり、変数を用意する数が減らせたりします。
配列がなければ、データ一つ一つに変数を用意する必要があり、できることが有限になってしまいます。
プログラミングをするうえで、必ず必要な要素になります。

ここでは、配列とListの2種類の扱い方を紹介します。
配列はListと違い2次元での使用ができる強みがありますが、要素数の変更は苦手です。
データ数が可変の場合は、Listを使うことをお勧めします。

配列

まずは配列の使い方を紹介します。

配列の宣言と初期化

配列の宣言はデータ型の後ろに[]を付けて記載します。
配列はnewで初期化して使用する必要があります。
newする際は[]の中に配列の要素数を指定します。

サンプルプログラム
class Program
{
    static void Main()
    {
        int[] list = new int[3];
        list[0] = 1;
        list[1] = 2;
        list[2] = 3;
        
        foreach (int i in list)
        {
            System.Console.WriteLine(i);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
1
2
3

サンプルプログラムの実行方法はトップページを参照してください。

最初に初期値を入れた状態で初期化する場合は、newの後ろに{}で値を指定します。

サンプルプログラム
class Program
{
    static void Main()
    {
        string[] strList = new string[] {"いち", "に", "さん", "よん", "ご"};
        foreach (string s in strList)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
いち
に
さん
よん
ご

データの参照と変更

配列の中を参照したり、値を変更する場合は、何番目に対する操作かを[]括りで連番を付けて指定します。
連番は0始まりで指定します。
二つ目の要素にアクセスする場合は1を指定します。

サンプルプログラム
class Program
{
    static void Main()
    {
        string[] strList = new string[] {"いち", "に", "さん", "よん", "ご"};
        
        // 2番目を変更する
        System.Console.WriteLine("変更前:"+strList[1]);
        strList[1] = "2";
        System.Console.WriteLine("変更後:"+strList[1]);

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
変更前:に
変更後:2

要素の追加

配列に要素を加えるには、System.Array.Resizeを使用します。
引数にはrefを付けた配列変数と変更後の要素数を指定します。

サンプルプログラム
class Program
{
    static void Main()
    {
        string[] strList = new string[] {"いち", "に"};
        
        System.Array.Resize(ref strList, strList.Length + 1);
        strList[strList.Length - 1] = "さん";
        
        foreach (string s in strList)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
いち
に
さん

このサンプルでは、配列.Lengthで現在の要素がわかるので、+1して要素を追加しています。
配列の連番は0始まりなので、strList.Length - 1を指定、最後の要素に対して値をセットしています。

要素の削除

配列は要素数の変更は得意ではありません。
途中の要素を削除する場合、値を詰めてから要素数を減らすという方法が必要になってきます。
それより後述するListを使用した方が簡単に削除することができます。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string[] strList = new string[] {"いち", "に", "さん"};
        
        // Listに変換
        List list = new List();
        list.AddRange(strList);
        
        // 要素を削除
        list.RemoveAt(1);
        
        // 配列に戻す
        strList = list.ToArray();
        
        foreach (string s in strList)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
いち
さん

List変数.AddRange(配列変数)で、配列をList変数にデータコピーします。
List変数.ToArray()でList変数を配列化できます。

配列をコピーする

配列データの複製にはSystem.Array.Copyを使用します。
なお、ただ=だけでcopyList = strListのように代入してしまうと、片方を更新したらもう片方も変わるようになります。

サンプルプログラム
class Program
{
    static void Main()
    {
        string[] strList = new string[] {"いち", "に", "さん"};
        
        string[] copyList = new string[strList.Length];
        System.Array.Copy(strList, copyList, strList.Length);
                
        foreach (string s in copyList)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
いち
に
さん

string[] copyList = new string[strList.Length];で同じ要素数の別配列を用意しています。
System.Array.Copyで第1引数にコピー元配列、第2引数にコピー先配列、第3引数にコピーする要素数を指定します。

配列をソートする

配列のソートはSystem.Array.Sortを使用します。

サンプルプログラム
class Program
{
    static void Main()
    {
        int[] iList = new int[] {2, 1, 5, 4, 3};
        
        System.Array.Sort(iList);
                
        foreach (int i in iList)
        {
            System.Console.WriteLine(i);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
1
2
3
4
5

二次元配列

Excelのような縦横に要素が並んだ配列を2次元と言います。
配列は2次元でデータを持つこともできます。

サンプルプログラム
class Program
{
    static void Main()
    {
        int[,] iList = new int[,]{ { 1, 2 },{ 3, 4 },{ 5, 6 } };
        
        for (int y = 0; y < iList.GetLength(0); y++)
        {
            for(int x = 0; x < iList.GetLength(1); x++)
            {
                System.Console.WriteLine((y+1)+"行目の"+(x+1)+"個目="+iList[y, x]);
            }
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
1行目の1個目=1
1行目の2個目=2
2行目の1個目=3
2行目の2個目=4
3行目の1個目=5
3行目の2個目=6

型名[,] 変数名 の形式で型を宣言します。
各要素の参照は変数名[縦の連番, 横の連番]の形式で行います。

List

次にListの使い方を紹介します。
配列との違いを比較して、使いやすい方を使ってください。

Listの宣言と初期化

Listの宣言はList<データ型>の形式で行います。
newで初期化して使用する必要があります。
newのときは最後に()を付けます。
Listは正確にはSystem.Collections.Generic.Listになるのですが、長くなってしまうので頭にusingディレクティブに記載します。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int>();
        list.Add(1);
        list.Add(2);
        list.Add(3);

        foreach (int i in list)
        {
            System.Console.WriteLine(i);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
1
2
3

最初に初期値を入れた状態で初期化する場合は、newの後ろに{}で値を指定します。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> strList = new List<string>() {"いち", "に", "さん", "よん", "ご"};
        foreach (string s in strList)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
いち
に
さん
よん
ご

データの参照と変更

データの参照や変更は配列と同じです。
[]括りで連番を付けて指定します。
0始まりで指定するのも配列と同じです。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> strList = new List<string>() {"いち", "に", "さん", "よん", "ご"};
        
        // 2番目を変更する
        System.Console.WriteLine("変更前:"+strList[1]);
        strList[1] = "2";
        System.Console.WriteLine("変更後:"+strList[1]);

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
変更前:に
変更後:2

要素の追加

Listに要素を加えるにはAdd(値)を呼び出すだけで可能です。
データの追加や削除は配列より得意です。
途中にデータを追加する場合もInsert(追加する箇所の連番, 値)だけでできます。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> strList = new List<string>() {"いち", "に"};
        
        // 一番後ろに追加
        strList.Add("さん");
        // 2番目に追加
        strList.Insert(1, "追加");
        
        foreach (string s in strList)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
いち
追加
に
さん

要素の削除

要素の削除もRemoveAt(連番)を呼び出すだけで可能です。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> strList = new List<string>() {"いち", "に", "さん"};

        strList.RemoveAt(1);
        
        foreach (string s in strList)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
いち
さん

Listをコピーする

Listの複製にはnewする際に()内に指定します。
配列と同じで、ただ=だけでcopyList = strListのように代入してしまうと、片方を更新したらもう片方も変わるようになります。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> strList = new List<string>() {"いち", "に", "さん"};
        
        List<string> copyList = new List<string>(strList);
                
        foreach (string s in copyList)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
いち
に
さん

Listをソートする

ListのソートはList変数.Sort()で可能です。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> iList = new List<int>() {2, 1, 5, 4, 3};
        
        iList.Sort();
                
        foreach (int i in iList)
        {
            System.Console.WriteLine(i);
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
1
2
3
4
5

二次元配列

Listの場合、二次元配列として使用するには入れ子にする必要があります。
ListをさらにListで持つことで実現します。

サンプルプログラム
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<List<int>> iList = new List<List<int>>() {
            new List<int>() { 1, 2 },
            new List<int>() { 3, 4 },
            new List<int>() { 5, 6 }
        };
        
        for (int y = 0; y < iList.Count; y++)
        {
            for(int x = 0; x < iList[y].Count; x++)
            {
                System.Console.WriteLine((y+1)+"行目の"+(x+1)+"個目="+iList[y][x]);
            }
        }

        System.Console.ReadKey();  // キー入力待ち
    }
}
実行結果
1行目の1個目=1
1行目の2個目=2
2行目の1個目=3
2行目の2個目=4
3行目の1個目=5
3行目の2個目=6