Manufaturação industrial
Internet das coisas industrial | Materiais industriais | Manutenção e reparo de equipamentos | Programação industrial |
home  MfgRobots >> Manufaturação industrial >  >> Industrial programming >> Linguagem C

Matriz irregular em C#

Matriz irregular em C#


Neste tutorial, aprenderemos sobre a matriz irregular do C#. Aprenderemos a declarar, inicializar e acessar o array irregular com a ajuda de exemplos.

Em C#, um array irregular consiste em vários arrays como seu elemento. No entanto, ao contrário dos arrays multidimensionais, cada array dentro de um array irregular pode ter tamanhos diferentes.

Antes de aprender sobre array irregular, certifique-se de saber sobre


Declaração de matriz irregular C#


Aqui está uma sintaxe para declarar uma matriz irregular em C#.
dataType[ ][ ] nameOfArray = new dataType[rows][ ];

Vejamos um exemplo,
// declare jagged array
int[ ][ ] jaggedArray = new int[2][ ];

Aqui,

Como sabemos que cada elemento de um array irregular também é um array, podemos definir o tamanho do array individual. Por exemplo,
// set size of the first array as 3
jaggedArray[0] = new int[3];

// set size of second array as 2
jaggedArray[1] = new int[2];

Inicializando matriz irregular


Existem diferentes maneiras de inicializar uma matriz irregular. Por exemplo,

1. Usando o número de índice

Uma vez que declaramos um array irregular, podemos usar o número do índice para inicializá-lo. Por exemplo,
// initialize the first array
jaggedArray[0][0] = 1;
jaggedArray[0][1] = 3;
jaggedArray[0][2] = 5;

// initialize the second array
jaggedArray[1][0] = 2;
jaggedArray[1][1] = 4;

Aqui,

2. Inicialize sem definir o tamanho dos elementos da matriz
// declaring string jagged array
int[ ][ ] jaggedArray = new int[2] [ ];

// initialize each array
jaggedArray[0] = new int[] {1, 3, 5};
jaggedArray[1] = new int[] {2, 4};

3. Inicialize ao declarar Jagged Array
int[ ][ ] jaggedArray = {
    new int[ ] {10, 20, 30},
    new int[ ] {11, 22},
    new int[ ] {88, 99}
};

Acessando elementos de um array irregular


Podemos acessar os elementos do array irregular usando o número do índice. Por exemplo,
// access first element of second array
jaggedArray[1][0];

// access second element of the second array
jaggedArray[1][1];

// access second element of the first array
jaggedArray[0][1];

Exemplo:C# Jagged Array

using System;

namespace JaggedArray {
  class Program {
    static void Main(string[] args) {

     // create a jagged array
     int[ ][ ] jaggedArray = {
         new int[] {1, 3, 5},
         new int[] {2, 4},
      };

     // print elements of jagged array
     Console.WriteLine("jaggedArray[1][0]: " + jaggedArray[1][0]);
     Console.WriteLine("jaggedArray[1][1]: " + jaggedArray[1][1]);

     Console.WriteLine("jaggedArray[0][2]: " + jaggedArray[0][2]);

     Console.ReadLine();
    }    
  }
}

Saída
jaggedArray[1][0]: 2
jaggedArray[1][1]: 4
jaggedArray[0][2]: 5



Aqui, dentro de uma matriz irregular,

Iterando através de uma matriz irregular


Em C#, podemos usar loops para percorrer cada elemento do array irregular. Por exemplo,
using System;

namespace JaggedArray {
  class Program {
    static void Main(string[] args) {

      // declare a jagged array
      int[][] jaggedArray = new int[2][];

      // set size of Jagged Array Elements
      jaggedArray[0] = new int[3];
      jaggedArray[1] = new int[2];

      // initialize the first array
      jaggedArray[0][0] = 1;
      jaggedArray[0][1] = 3;
      jaggedArray[0][2] = 5;

      // initialize the second array
      jaggedArray[1][0] = 2;
      jaggedArray[1][1] = 2;
      	 
      // outer for loop
      for (int i = 0; i < jaggedArray.Length; i++) {

        Console.Write("Element "+ i +": ");
        // inner for loop
        for (int j = 0; j < jaggedArray[i].Length; j++) {
          Console.Write(jaggedArray[i][j] + " ");
         }
      Console.WriteLine();
      }
      Console.ReadLine();
    } 
  }
}

Saída
Element 0: 1 3 5
Element 1: 2 2

No exemplo acima, usamos um loop for aninhado para percorrer o array irregular. Aqui,

1. Externo para loop

2. Interno para loop

Matriz irregular com matriz multidimensional


Em C#, também podemos usar arrays multidimensionais como Jagged Array Elements. Por exemplo,
int[ ][ , ] jaggedArrayTwoD = new int[2][ , ] {
    	new int[,] { {1, 8}, {6, 7} },
    	new int[,] { {0, 3}, {5, 6}, {9, 10} }
};

Aqui, cada elemento do array irregular é um array multidimensional:

Vejamos um exemplo,
using System;

namespace JaggedArray  {
  class Program {
    static void Main(string[] args)  {
  	 
      // declare and initialize jagged array with 2D array
      int[][,] jaggedArray = new int[3][ , ]  {
          new int[ , ] { {1, 8}, {6, 7} },
          new int[ , ] { {0, 3}, {5, 6}, {9, 10} },
          new int[ , ] { {11, 23}, {100, 88}, {0, 10} }
      };

      Console.WriteLine(jaggedArray[0][0, 1]);
      Console.WriteLine(jaggedArray[1][2, 1]);
      Console.WriteLine(jaggedArray[2][1, 0]);

      Console.ReadLine();
    }    
  }
}

Saída
8
10
100

No exemplo acima, observe o código,
jaggedArray[0][0, 1]

Aqui,

Linguagem C

  1. Matrizes C#
  2. Passando array para uma função na programação C++
  3. Copiar Matrizes Java
  4. Matrizes em C++ | Declare | Inicializar | Ponteiro para exemplos de matriz
  5. Alocação dinâmica de matrizes em C++ com exemplo
  6. Tutorial de coleções de C# com exemplos
  7. Como criar uma matriz de objetos em Java
  8. MATLAB - Matrizes
  9. Técnicas de Inspeção de Matriz de Grade de Bola
  10. Matriz de nanosensores de língua eletrônica