Home >Backend Development >C#.Net Tutorial >How to convert a two-dimensional array to a one-dimensional array in C#?

How to convert a two-dimensional array to a one-dimensional array in C#?

王林
王林forward
2023-09-20 16:01:101612browse

How to convert a two-dimensional array to a one-dimensional array in C#?

Set a two-dimensional array and a one-dimensional array−

int[,] a = new int[2, 2] {{1,2}, {3,4} };
int[] b = new int[4];

Convert the 2D array to a 1D array, and set the previously declared two-dimensional array to a one-dimensional array −

for (i = 0; i < 2; i++) {
   for (j = 0; j < 2; j++) {
      b[k++] = a[i, j];
   }
}

The following is a complete code example to convert a two-dimensional array to a one-dimensional array:

Example

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

The above is the detailed content of How to convert a two-dimensional array to a one-dimensional array in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete