一、List
List是一種強類型列表
List在大多數情況下比ArrayList執行的更好並且是類型安全的
using System;
using System.Collections;
//使用泛型集合,需要先引入命名空間
using System.Collections.Generic;
namespace Lesson_23
{
public class Person{
}
class MainClass
{
public static void Main (string[] args)
{
List<Person> l1 = new List<Person> ();
//1、聲明一個List對象arr
List<string> arr = new List<string> ();
//ArrayList中對元素類型沒有限制,List對元素類型有限制
//添加元素使用Add()方法
arr.Add("hello");
arr.Add("world");
arr.Add("lanou");
//使用Inser()f方法插入元素
//把字符串“老王”插入到下標爲1的位置
arr.Insert (1,"老王");
//使用Remove()方法刪除指定元素
arr.Remove("hello");
//使用RemoveAt()方法刪除指定下標位置的元素
arr.RemoveAt(1);
int c=arr.Count;
//使用Contains()方法判斷指定的元素是否存在於List中
bool b=arr.Contains("world");
if (b) {
Console.WriteLine ("world 存在於list中");
} else {
Console.WriteLine ("world 不存在於list中");
}
//a可以使用下標訪問List中的元素
arr[0]="你好!";
string str=arr[1];
Console.WriteLine(str);
//使用Clear()清空整個List
arr.Clear();
//1、ArrayList 對元素的類型沒有限制
ArrayList a = new ArrayList ();
a.Add ("hello");
a.Add (14);
a.Add ("15.67f");
//因爲ArrayList對元素類型沒有限制,系統會把這些元素當做object類型對象存儲
string s= (string)a [0];
//Arraylist 使用時效率會低一些
}
}
}