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

王林
Release: 2023-09-20 16:01:10
forward
1539 people have browsed it

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];
Copy after login

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];
   }
}
Copy after login

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template