更新:2007 年 11 月
儲存資料相關項目的群組是大部分軟體應用程式的基本必要條件﹔有兩種主要方式可以執行這個動作,分別是使用陣列和集合。
陣列
陣列是指相同型別之物件的集合。因為陣列可以是任何長度,可以用來儲存成千上萬個物件,但是其大小必須在建立陣列時就決定。陣列中的每個項目都可由索引存取,索引只是一個表示物件儲存在陣列中哪個位置的數字。陣列可用來儲存參考型別 (Reference Type) 和實值型別 (Vaule Type)。
單一維度的陣列
陣列是物件的索引集合。一維物件陣列宣告方式如下所示:
type[] arrayName;
通常您會同時初始化陣列中的元素,如下所示:
int[] array = new int[5];
數值陣列元素的預設值為零,參考元素預設為 null,但是您可以在陣列建立期間初始化其值,如下所示:
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
或甚至如下所示:
int[] array2 = {1, 3, 5, 7, 9};
陣列會使用以零起始的索引,所以陣列中的第一個元素是元素 0。
string[] days = {"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"};
System.Console.WriteLine(days[0]); // Outputs "Sun"
多維陣列
在概念上來說,具有兩個維度的多維陣列就類似方格,具有三個維度的多維陣列就像立方體。
// declare multidimension array (two dimensions)
int[,] array2D = new int[2,3];
// declare and initialize multidimension array
int[,] array2D2 = { {1, 2, 3}, {4, 5, 6} };
// write elements in a multidimensional array
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
array2D[i,j] = (i + 1) * (j + 1);
}
}
// read elements in a multidimensional array
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
System.Console.Write(array2D[i,j]);
}
System.Console.WriteLine();
}
不規則陣列
多維陣列的變化是不規則陣列,也就是陣列的陣列。不規則陣列是一維陣列,而每個元素本身是一個陣列。元素陣列不需要全部都是相同大小。
您可以如下所示宣告不規則陣列:
int[][] jaggedArray = new int[3][];
這樣做會建立三個陣列的陣列,這些陣列可以進行初始化,如下所示:
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
使用 foreach 陳述式
foreach 陳述式通常用來存取儲存在陣列中的每個元素:
int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
System.Console.Write("{0} ", i);
}
//Output: 4 5 6 1 2 3 -2 -1 0
物件的陣列
建立物件陣列與建立像是整數的簡單資料型別陣列不同,其中涉及了兩個部分的程序。首先要宣告陣列,然後必須建立儲存在陣列中的物件。這個範例建立了定義音訊 CD 的類別。然後建立儲存 20 片音訊 CD 的陣列。
namespace CDCollection
{
// Define a CD type.
class CD
{
private string album;
private string artist;
private int rating;
public string Album
{
get {return album;}
set {album = value;}
}
public string Artist
{
get {return artist;}
set {artist = value;}
}
public int Rating
{
get {return rating;}
set {rating = value;}
}
}
class Program
{
static void Main(string[] args)
{
// Create the array to store the CDs.
CD[] cdLibrary = new CD[20];
// Populate the CD library with CD objects.
for (int i=0; i<20; i++)
{
cdLibrary[i] = new CD();
}
// Assign details to the first album.
cdLibrary[0].Album = "See";
cdLibrary[0].Artist = "The Sharp Band";
cdLibrary[0].Rating = 10;
}
}
}
集合
陣列只是使用 C# 儲存資料集之諸多選項中的其中一個。您所選取的選項取決於幾個因素,例如您想要如何管理或存取這些項目。例如,如果您必須將項目插入到集合的開頭或中間,「清單」(List) 通常會比陣列來得快。其他類型的集合類別包括對應、樹狀目錄和堆疊;每個類型都有其獨特的優點。如需詳細資訊,請參閱 System.Collections 和 System.Collections.Generic。
下列範例將示範如何使用 List<T> 類別。請注意,與 Array 類別不同的是項目可以插入到清單中間。這個範例限制清單中的項目,這樣它們就必須是字串。
public class TestCollections
{
public static void TestList()
{
System.Collections.Generic.List<string> sandwich = new System.Collections.Generic.List<string>();
sandwich.Add("bacon");
sandwich.Add("tomato");
sandwich.Insert(1, "lettuce");
foreach (string ingredient in sandwich)
{
System.Console.WriteLine(ingredient);
}
}
}