How to convert Two-dimensional array to a Single array?

Asked

Viewed 186 times

4

I have the following definition of Two-dimensional Array:

int[,] arrayBidimensional = new int[3, 3]
{
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

The above variable does not have a method .ToArray() for the value to be converted to a simple array.

How do I convert this array two-dimensional for a int[ ] instead of int[,] ? There is a way simple to do this?

  • The simplest way is to traverse the 2 dimensions of the array (with a for), and assign the values to a second array.

  • António Campos, you can illustrate?

2 answers

6


You can cast.. won’t be the most efficient but it’s simple:

int[] array1d = arrayBidimensional.Cast<int>().ToArray();
  • In fact, efficiency is the greatest possible, speaking of complexity. It’s the same efficiency as the method of my answer. The only thing that differs is to have some extra indirect, are a 2 more calls, a cast attempt and then a cast for each item - that, honestly, I do not know what happens, since the item is already of the type that tries to cast the.

4

The algorithm is simple: scroll through the array and create a new one-dimensional.

using System;

class MainClass {
    public static void Main (string[] args) {
        int[,] arrayBidimensional = new int[3, 3]
        {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        var linhas = arrayBidimensional.GetLength(0);
        int colunas = arrayBidimensional.GetLength(1);
        var novoArray = new int[linhas * colunas];

        for(int i = 0; i < linhas; i++) {
            for(int j = 0; j < colunas; j++) {
                var indice = colunas * i + j;          
                novoArray[indice] = arrayBidimensional[i, j];

                Console.WriteLine($"{indice} = {novoArray[indice]}");
            }
        }
    }
}

See working on Repl.it

On second thought, the above code can still be simplified to

using System;

class MainClass {
    public static void Main (string[] args) {
        int[,] arrayBidimensional = new int[3, 3]
        {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        var novoArray 
            = new int[arrayBidimensional.GetLength(0) * arrayBidimensional.GetLength(1)];

        int indice = 0;
        foreach(var item in arrayBidimensional) {
            novoArray[indice] = item;
            Console.WriteLine($"{indice} = {novoArray[indice]}");
            indice++;
        }
    }
}

See working on Repl.it

  • If I edit this Repl.it code will this change reflect on your code or is the change unique to me? I’m asking just out of curiosity, because I’m not going to make any changes.

  • 1

    @Augustovasques doesn’t change, it’s only for those who edited.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.