如何在 C# 中將一個 2D 陣列轉換為一個 1D 陣列?


定義一個二維陣列和一個一維陣列 −

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];
   }
}

以下是在 C# 中將二維陣列轉換為一維陣列的完整程式碼 −

示例

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();
      }
   }
}

更新於: 21-Jun-2020

3K+ 瀏覽次數

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告