陣列是各語言最常用的資料結構,本文主要介紹C#操作陣列的方法,以供有興趣的朋友參考。


陣列是一種資料結構,其中會包含多個相同型別的變數。陣列是用型別宣告:
type[] arrayName;
 
C#陣列有下列屬性:
* 陣列是以0為起始索引,即包含 n 個元素的陣列建立索引時,會從 0 開始,一直到 n-1 為止。
* 陣列可以是一維、多維或不規則。
* 數值陣列元素的預設值會設定為零,而參考元素則設定為 null
* 不規則陣列是指包含陣列的陣列,因此其元素為參考型別,而且會初始化為 null
* 陣列元素可以是任何型別,包括陣列型別。
* 陣列型別是從抽象基底型別 Array 衍生的參考型別。由於此型別會實作 IEnumerable IEnumerable,您可以在 C# 中的所有陣列上使用 foreach 反覆運算。
 
Declaring Arrays(宣告)
Example:
Single-dimensional arrays:
int[] numbers;
 
Multidimensional arrays:
string[,] names;
 
Array-of-arrays (jagged):
byte[][] scores;
 
Initializing Arrays(初始化)
C# array 都是 Objects,使用前都必須先初始化。
Note                如果 Array 宣告時未初始化,其元素將會被自動初始化為個型態的預設值,數值為 0,其他參考元素為NULL
 
Example:
Single-Dimensional Array
int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {"Matt", "Joanne", "Robert"};
- or -
int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};
- or -
int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Matt", "Joanne", "Robert"};
 
Multidimensional Array
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };
- or -
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };
- or -
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };
 
Jagged Array (Array-of-Arrays)
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
- or -
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
-or-
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
 
Accessing Array Members(使用)
Example:
Single-Dimensional Array
int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
numbers[4] = 5;
 
Multidimensional array
int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;
 
Jagged array
int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5}
};
 
設定值
numbers[0][0] = 58;
numbers[1][1] = 667;
 
Arrays are Objects
C# arrays 實際上是個物件。 System.Array 為最基礎的類別,提供了許多有用的 methods/properties
Example:
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;
 
Using foreach on Arrays
利用 foreach 可以簡單且清楚的方法來逐一查看陣列中的元素。
 
Example:
Single-Dimensional Array
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
   System.Console.WriteLine(i);
}
 
Multidimensional Array
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
   Console.Write("{0} ", i);
}
 
The output of this example is:
9 99 3 33 5 55
arrow
arrow
    文章標籤
    C# Array
    全站熱搜

    mark528 發表在 痞客邦 留言(0) 人氣()