在C#當中,集合有我們常用的Arraylist(動態數組),Hashtable(關健字和值的尋找表)和不常用的BitArray(位元組),Queue(先進先出的集合),SortedList(有序例表),Stack(後進先出的棧)等等。
其實集合就是將一組有序的資料群組合在一起並能對其進行有效處理。在這裡我們主要介紹常用的Arraylist與Hashtable。
Arraylist
類似於一維動態數組,在Arraylist中可以存放任何對像,Arraylist的常用方法有以下三種:增加元素Add(),插入元素Insert(),刪除元素Remove()。
例:
首先要引入命名空間:using System.Collections;
Hashtable
是用來存入鍵/值對的集合,如果有需要同時存放鍵並對應有值的時候我們可以用Hashtable 。
例:
Code
public static void Main()
{
Hashtable hash = new Hashtable(); //定義一個Hashtable集合
hash.Add("one", 1);//為集合中填加健與值
hash.Add("two", 2);
hash.Add("three", 3);
hash.Add("four", 4);
foreach (string a in hash.Keys)//遍曆所有的健值
{
Console.WriteLine("{0},{1}", a, hash[a]);//輸出健與值
}
}
Code
public static void Main()
{
ArrayList arr = new ArrayList();
arr.Add(10);//為集合添加一個值
arr.Add(10);//添加第二個值
arr.Insert(0, 8);//在第0索引位置插入一個值8
Console.WriteLine(arr.IndexOf(10, 2));//搜尋指從索引從0到2的值為10的數量.
foreach (int a in arr)//遍曆集合arr
{
Console.WriteLine(a);www.elivn.com
}
}