集合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);
}
}
}