コレクション

C#入門④ コレクション

コレクションとは?

コレクションとは、複数のデータをまとめて管理するための仕組みです。
C#では配列(Array)に加えて、柔軟で便利な コレクションクラス が用意されています。

代表的なコレクションは以下の通りです。

  • List<T>
  • Dictionary<TKey, TValue>
  • Queue<T>
  • Stack<T>

List(リスト)

順序付きで要素を保持し、サイズを動的に変更できます。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> fruits = new List<string>();
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Cherry");

        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }

        Console.WriteLine("2番目: " + fruits[1]); // Banana
    }
}

Dictionary<TKey, TValue>(辞書)

キーと値のペアでデータを保持します。

Dictionary<string, int> scores = new Dictionary<string, int>();
scores["Taro"] = 80;
scores["Hanako"] = 90;

Console.WriteLine(scores["Taro"]); // 80

Queue(キュー)

FIFO(先入れ先出し)のコレクションです。

Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);

Console.WriteLine(queue.Dequeue()); // 1
Console.WriteLine(queue.Dequeue()); // 2

Stack(スタック)

LIFO(後入れ先出し)のコレクションです。

Stack<string> stack = new Stack<string>();
stack.Push("A");
stack.Push("B");
stack.Push("C");

Console.WriteLine(stack.Pop()); // C
Console.WriteLine(stack.Pop()); // B

コレクション操作の便利メソッド

LINQと組み合わせることで、コレクションを効率的に操作できます。

using System.Linq;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

var even = numbers.Where(n => n % 2 == 0);

foreach (int n in even)
{
    Console.WriteLine(n); // 2, 4
}

まとめ

  • List<T> は配列より柔軟にデータを管理できる
  • Dictionary<TKey, TValue> でキーと値のペアを扱える
  • Queue<T> はFIFO、Stack<T> はLIFOのデータ構造
  • LINQを使えばコレクションを効率的に処理できる