ArrayList 屬於非泛型集合,存入時會發生裝箱,取出需拆箱並強制轉型,效能差且易發生執行期錯誤。現代 C# 開發應優先使用 List<T>。
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
var products = new List<Product>();
products.Add(new Product { Id = 1001, Name = "蘋果", Quantity = 10, Price = 1.2m });
// 1. 依商品編號查詢
var target = products.FirstOrDefault(p => p.Id == 1001);
if (target != null)
{
Console.WriteLine($"{target.Name} - 單價: {target.Price}");
}
// 2. 修改庫存
target.Quantity -= 2;
// 3. 遍歷顯示
foreach (var p in products)
{
Console.WriteLine($"{p.Id}\t{p.Name}\t{p.Quantity}\t{p.Price}");
}
若資料量大且頻繁依 ID 查詢,可改用 Dictionary<int, Product>:
var dict = products.ToDictionary(p => p.Id);
Product p = dict[1001]; // O(1) 直接取得
List<T> 管理集合,享受編譯期型別檢查與 IntelliSense。Dictionary<K, V>。這才是 C# 正統、高效、可維護的資料處理方式。