Maison  >  Article  >  développement back-end  >  Comment convertir un tableau bidimensionnel en tableau unidimensionnel en C# ?

Comment convertir un tableau bidimensionnel en tableau unidimensionnel en C# ?

王林
王林avant
2023-09-20 16:01:101452parcourir

Comment convertir un tableau bidimensionnel en tableau unidimensionnel en C# ?

Définissez un tableau bidimensionnel et un tableau unidimensionnel−

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

Convertissez le tableau 2D en un tableau 1D, définissez le tableau bidimensionnel précédemment déclaré en un tableau unidimensionnel−

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

Ce qui suit est pour convertir le tableau bidimensionnel en exemple de code complet pour un tableau 1D :

Exemple

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer