Listで長さが変わるデータを扱う
配列は作成時に長さが決まります。あとから要素を追加・削除したい場合は、List<T> が便利です。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> scores = new List<int>();
scores.Add(80);
scores.Add(65);
scores.Add(92);
Console.WriteLine(scores.Count); // 3
Console.WriteLine(scores[1]); // 65
}
}
List<int> は整数を保存するListです。文字列なら List<string> のように、山括弧の中で要素の型を指定します。
よく使う操作
| 操作 | 意味 |
|---|---|
Add(value) |
末尾に追加 |
Count |
要素数を取得 |
Remove(value) |
指定した値を削除 |
RemoveAt(index) |
指定位置の要素を削除 |
Clear() |
すべて削除 |
Listを順番に処理する
var numbers = new List<int> { 3, 5, 8 };
numbers.Add(2);
int total = 0;
foreach (int number in numbers)
{
total += number;
}
Console.WriteLine(total);
配列とListのどちらを使うかは、要素数が固定か、追加・削除が必要かで考えましょう。