Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing multidimensional arrays in c# (with other arrays)

In C#, it's possible to initialize a multidimensional array using constants like so:

Object[,] twodArray = new Object[,] { {"00", "01", "02"}, 
                                      {"10", "11", "12"},
                                      {"20", "21", "22"} };

I personally think initializing an array with hard coded constants is kind of useless for anything other than test exercises. Anyways, what I desperately need to do is initialize a new multidimensional array as above using existing arrays. (Which have the same item count, but contents are of course only defined at runtime).

A sample of what I would like to do is.

Object[] first  = new Object[] {"00", "01", "02"};
Object[] second = new Object[] {"10", "11", "12"};
Object[] third  = new Object[] {"20", "21", "22"};
Object[,] twodArray = new Object[,] { first, second, third };

Unfortunately, this doesn't compile as valid code. Funny enough, when I tried

Object[,] twodArray = new Object[,] { {first}, {second}, {third} };

The code did compile and run, however the result was not as desired - a 3 by 3 array of Objects, what came out was a 3 by 1 array of arrays, each of which had 3 elements. When that happens, I can't access my array using:

Object val = twodArray[3,3];

I have to go:

Object val = twodArray[3,1][3];

Which obviously isn't the desired result.

So, is there any way to initialize this new 2D array from multiple existing arrays without resorting to iteration?

like image 865
Alain Avatar asked Aug 26 '11 13:08

Alain


People also ask

What is multi dimensional array in C explain with example?

A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns (think of a table). A 3D array adds another dimension, turning it into an array of arrays of arrays.

How do you declare and initialize a multidimensional array explain by example?

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.


1 Answers

This would work if you switched to jagged arrays:

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

int[][] jagged = new[] { arr1, arr2, arr3 };

int six = jagged[1][2];

Edit To clarify for people finding this thread in the future

The code sample above is also inadequate as it results in an array of arrays (object[object[]]) rather than a jagged array (object[][]) which are conceptually the same thing but distinct types.

like image 182
MattDavey Avatar answered Sep 19 '22 08:09

MattDavey