ArrayList list = new ArrayList();
list.Add(new Employee("Zxjay", 20, "010-123456"));
list.Add(new Employee("Andy", 30, "020-123456"));
list.Add(new Employee("Bill", 50, "010-3456789"));
list.Add(new Employee("Lee", 40, "0532-234567"));
所有元素視為 object,存入值型別需裝箱,取出需拆箱並強制轉型,效能損耗大且無編譯期型別安全。
class SortArrayList : IComparer
{
public int Compare(object x, object y)
{
Employee a = x as Employee;
Employee b = y as Employee;
return a.Name.CompareTo(b.Name);
}
}
list.Sort(new SortArrayList());
ArrayList selectedList = new ArrayList();
foreach (object obj in list)
{
Employee emp = obj as Employee;
if (emp != null && emp.Phone.StartsWith("010") && emp.Age < 50)
{
selectedList.Add(emp);
}
}
private void ShowList(ArrayList list)
{
Console.WriteLine("{0,-20}{1,-5}{2}", "Name", "Age", "Phone");
foreach (object obj in list)
{
Employee emp = obj as Employee;
if (emp != null)
{
Console.WriteLine("{0,-20}{1,-5}{2}", emp.Name, emp.Age, emp.Phone);
}
}
}
List<Employee> 移除裝箱/拆箱,編譯期強型別檢查delegate(Employee x, Employee y) { ... } 簡化排序/篩選邏輯傳遞
list.Sort(delegate(Employee x, Employee y) { return x.Name.CompareTo(y.Name); });
List<Employee> listBeijing = list.FindAll(
delegate(Employee emp) { return emp.Phone.StartsWith("010") && emp.Age < 50; }
);
private void ShowList(IList<Employee> list)
{
Console.WriteLine("{0,-20}{1,-5}{2}", "Name", "Age", "Phone");
foreach (Employee emp in list)
{
Console.WriteLine("{0,-20}{1,-5}{2}", emp.Name, emp.Age, emp.Phone);
}
}
| 時代 | 集合型別 | 型別安全 | 排序/篩選語法 | 效能 |
|---|---|---|---|---|
| .NET 1.x | ArrayList | 無(運行時檢查) | IComparer + 手動迴圈 | 裝箱/拆箱開銷大 |
| .NET 2.0 | List<T> | 編譯期強型別 | 匿名方法 | 無裝箱,效能大幅提升 |
| .NET 3.5 | List<T> + LINQ | 編譯期強型別 + IntelliSense | Lambda + 查詢語法 | 同 2.0,開發效率最高 |
從 ArrayList 到 List<T>,再到 LINQ,每一次演進都在解決前一代的痛點:型別安全、程式碼冗長、可讀性。理解這段歷史,有助於體會 LINQ 設計初衷與優雅之處。