設定一個二維數組和一個一維數組−
int[,] a = new int[2, 2] {{1,2}, {3,4} }; int[] b = new int[4];
將2D數組轉換為1D數組,將先前聲明的二維數組設為一維數組−
for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { b[k++] = a[i, j]; } }
以下是將二維數組轉換為一維數組的完整程式碼範例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Program { class twodmatrix { static void Main(string[] args) { int[, ] a = new int[2, 2] { { 1, 2 },{ 3, 4 } }; int i, j; int[] b = new int[4]; int k = 0; Console.WriteLine("Two-Dimensional Array..."); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i, j]); } } Console.WriteLine("One-Dimensional Array..."); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { b[k++] = a[i, j]; } } for (i = 0; i < 2 * 2; i++) { Console.WriteLine("{0}\t", b[i]); } Console.ReadKey(); } } }
以上是如何在C#中將一個二維數組轉換為一維數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!