在 C# 開發中,傳統陣列有一個固有缺陷:容量固定。當你無法預先確定資料筆數時,宣告太小會導致溢位,宣告太大則浪費記憶體。例如讓使用者輸入資料、從網站爬取資訊,或是處理不定數量的物件集合,固定大小的陣列顯然不是好選擇。
List<T> 是一個動態擴容的陣列,內建豐富的方法與屬性,自動管理內部儲存空間。當元素數量超過容量時,會自動成長(預設雙倍擴容),開發者無需手動處理記憶體配置。
| 成員 | 說明 |
|---|---|
Capacity | 取得/設定可容納元素數量,超過時自動增長,可呼叫 TrimExcess() 縮減至實際大小 |
Count | 取得目前實際元素數量(唯讀) |
Item[int] | 索引器,透過索引存取元素 |
Add(T) | 在尾端新增單一元素 |
AddRange(IEnumerable<T>) | 批次新增多個元素 |
BinarySearch(T) | 於已排序清單中二分搜尋 |
Clear() | 移除所有元素 |
Contains(T) | 判斷元素是否存在 |
Find/Predicate<T> | 尋找第一個符合條件的元素 |
FindAll/Predicate<T> | 回傳所有符合條件的元素 |
Sort() | 原地排序(預設遞增) |
ToArray() | 複製為新陣列 |
using System;
using System.Collections.Generic;
namespace ListDemo
{
public class Employee
{
public int EmpID { get; set; }
public Employee(int id) => EmpID = id;
public override string ToString() => EmpID.ToString();
}
class Program
{
static void Main()
{
var empList = new List<Employee>();
var intList = new List<int>();
// 填充資料
for (int i = 0; i < 5; i++)
{
empList.Add(new Employee(i + 100));
intList.Add(i * 5);
}
// 列印整數清單
Console.WriteLine("整數清單:");
foreach (var n in intList) Console.Write($"{n} ");
Console.WriteLine();
// 列印員工清單
Console.WriteLine("員工清單:");
foreach (var e in empList) Console.Write($"{e} ");
Console.WriteLine();
Console.WriteLine($"\nempList.Capacity: {empList.Capacity}"); // 預設 16(.NET 版本可能不同)
Console.WriteLine($"empList.Count: {empList.Count}"); // 5
}
}
}
Count == Capacity 時,新容量 = 目前容量 × 2(最小增長 4)。Capacity,但不得小於 Count,否則拋出 ArgumentOutOfRangeException。TrimExcess() 將容量壓縮至 Count(若使用率超過 90% 則不處理)。new List<T>(estimatedCount) 避免多次擴容複製。LinkedList<T> 或 Queue<T>/Stack<T>。Sort(),否則結果未定義。List<T> 是 C# 最常用的集合類型,結合了陣列的隨機存取效能與動態擴容的彈性,掌握其容量機制與核心 API,能讓資料處理更高效、程式碼更簡潔。