C#の List<T> は、可変長の配列のようなものです。配列と違って、要素の追加・削除が簡単にできるため、実用性が高いです。
System.Collections.Generic 名前空間に含まれています。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> fruits = new List<string>();
fruits.Add("りんご");
fruits.Add("バナナ");
fruits.Add("みかん");
Console.WriteLine("最初の果物: " + fruits[0]);
Console.WriteLine("合計: " + fruits.Count + "個");
}
}
List<string> は「文字列のリスト」を表します。Add() で要素を追加します。Count で現在の要素数を取得できます。fruits[0] でアクセスできます。using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 100, 200, 300 };
foreach (int n in numbers)
{
Console.WriteLine("数値: " + n);
}
}
}
Add(value):要素の追加Remove(value):指定の要素を削除Contains(value):指定の要素を含むか判定Clear():すべての要素を削除数値リストに対して以下の操作を行ってください:
10, 20, 30 を追加する20 が含まれているか判定する