數組是一種數據結構,它可以包含同一類型的多個元素,C#中的數組元素從零開始。
數組可分為:簡單數組、多維數組和鋸齒數組。
1、聲明及初始化
int [] x = new int[5];
聲明了數組后,就必須為數組分配內存,以保存數組的所以元素。數組是引用類型,所以必須給它分配推上的內存。使用new運算符,指定數組中元素的類型和數量來初始化數組的變量。
1. 使用數組初始化器為數組的每個元素賦值
int [] x = new int[5]{10,6,7,15,8};2. 不指定數組的大小
int [] x = new int[]{10,6,7,15,8};3. 簡化的形式
int [] x = {10,6,7,15,8};2、訪問數組元素
1. 使用索引器傳遞元素編號訪問數組
int [] x = {10,6,7,15,8};Console.WriteLine(x[0]); // 10Console.WriteLine(x[1]); // 62. 使用For循環遍歷
int[] x = { 10, 6, 7, 15, 8 };for (int i = 0; i < x.Length; i++){     Console.Write(x[i]+" "); // 10 6 7 15 8}3. 使用foreach循環遍歷
int[] x = { 10, 6, 7, 15, 8 };foreach (var i in x){    Console.Write(i + " "); // 10 6 7 15 8 }4. 使用Array.Sort排序
int[] x = { 10, 6, 7, 15, 8 };Array.Sort(x); foreach (var i in x){   Console.Write(i + " "); // 6 7 8 10 15}5. 冒泡排序
int[] array = { 10, 6, 7, 15, 8 };int temp = 0;for (int i = 0; i < array.Length - 1; i++){    for (int j = i + 1; j < array.Length; j++)    {        if (array[j] < array[i])        {            temp = array[i];            array[i] = array[j];            array[j] = temp;        }    }}foreach (var i in array){    Console.Write(i + " ");   // 6 7 8 10 15}6. 數組求差集、交集、并集
int[] x = { 10, 6, 7, 15, 8 };int[] y = { 20, 9, 15, 2, 7 };// 差集var z1 = x.Except(y);foreach (var i in z1){    Console.Write(i + " "); // 10 6 8}Console.WriteLine("");// 交集var z2 = x.Intersect(y);foreach (var i in z2){    Console.Write(i + " ");  // 7 15 }Console.WriteLine("");// 并集var z3 = x.Union(y);foreach (var i in z3){    Console.Write(i + " "); // 10 6 7 15 8 20 9 2 }多維數組是用兩個或多個整數來索引。
1. 二維數組聲明及初始化
int[,] y1 = new int[2, 2];y[0, 0] = 1;y[0, 1] = 2;y[1, 0] = 3;y[1, 1] = 4;
int[,] y2 = { { 1, 2 }, { 3, 4 } };2. 三維數組
int[,,] y3 ={    {{1, 2}, {3, 4}},    {{5, 6}, {7, 8}},    {{9, 10}, {11, 12}},};二維數組是一個完整的矩形,而鋸齒數組大大小設置比較靈活,在鋸齒數組中,每一行都可以有不同的大小。
int[][] j = new int[3][];j[0] = new int[2] { 1, 2 };j[1] = new int[5] { 3, 4, 5, 6, 7 };j[2] = new int[3] { 8, 9, 10 };新聞熱點
疑難解答