集合ArrayList小練習:
已實作Car類,屬性包括車名Name、産地ProductArea
建立三個Car對象,添加到ArrayList集合中,并輸出元素個數
輸出其中一個Car對象的Name屬性
删除下标為1的元素,并輸出目前元素個數
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
//已實作Car類,屬性包括車名Name、産地ProductArea
class Car
{
public string name;
public string productArea;
public Car(){
}
public Car(string name, string productArea)
{
this.name = name;
this.productArea = productArea;
}
}
class Program
{
static void Main(string[] args)
{
//建立三個Car對象,添加到ArrayList集合中,并輸出元素個數
Car[] car = new Car[]{
new Car("001","河北"),
new Car("002","河北"),
new Car("003","河北"),
};//初始化對象數組的方式
//輸出其中一個Car對象的Name屬性
ArrayList carList = new ArrayList();
for (int i = 0; i < car.Count();i++ )
{
carList.Add(car[i]);
}
Console.WriteLine("現有車輛:"+carList.Count);
Console.WriteLine("Car1車的相關資訊(車名):"+car[0].name);
//删除下标為1的元素,并輸出目前元素個數
carList.RemoveAt(1);
Console.WriteLine("删除下标為1的元素,還有車輛:"+carList.Count);
//周遊輸出目前集合中Car對象的Name屬性
foreach(object ob in carList){
Car c = (Car)ob;
Console.WriteLine("現有車輛的相關資訊(車名)"+c.name);
}
//删除一個ArrayList元素有幾種方法?======目前我知道有4種。
//<1>carList.RemoveAt(1);
//<2>carList.Remove(car[0]);
//<3>carList.RemoveRange(0,2);
//<4>carList.Clear();
Console.WriteLine("還有車輛:" + carList.Count);
Console.WriteLine("=================作業已完成===================");
//ArrayList和List<T>的主要差別是什麼?
List<Car> carList1=new List<Car>();
for (int i = 0; i < car.Count();i++)
{
carList1.Add(car[i]);
}
Console.WriteLine(carList1.Count);
carList1.RemoveAt(2);
Console.WriteLine(carList1.Count);
}
}
}