初識化集合:
這進行類型轉換。
ArrayList list;
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"));
排序:
需實現IComparer接口。
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:G}{1,-5:G}{2}", "Name", "Age", "Phone");
foreach (object obj in list)
{
Employee emp = obj as Employee;
if (emp != null)
{
Console.WriteLine("{0,-20:G}{1,-5:G}{2}", emp.Name, emp.Age, emp.Phone);
}
}
}
.Net 2.0時代
加入了泛型和匿名方法,代碼量減少,邏輯清晰了許多,編譯期間強類型檢查和去掉了強制類型轉換及裝箱、拆箱操作。
定義實體類跟.Net 1.1時代一樣。
排序選擇直接用匿名方法實現:
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:G}{1,-5:G}{2}", "Name", "Age", "Phone");
foreach (Employee emp in list)
{
Console.WriteLine("{0,-20:G}{1,-5:G}{2}", emp.Name, emp.Age, emp.Phone);
}
}