Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Arrays in C#

  • I need to know how to initialize array of arrays in C#..
  • I know that there exist multidimensional array, but I think I do not need that in my case! I tried this code.. but could not know how to initialize with initializer list..

    double[][] a=new double[2][];// ={{1,2},{3,4}};

Thank you

PS: If you wonder why I use it: I need data structure that when I call obj[0] it returns an array.. I know it is strange..

Thanks

like image 749
Betamoo Avatar asked Apr 30 '10 21:04

Betamoo


People also ask

Can you have an array of arrays in C?

Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays.

Can you have an array of arrays?

A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.

How do you define an array of arrays?

To initialize an array of arrays, you can use new keyword with the size specified for the number of arrays inside the outer array. int[][] numbers = new int[3][]; specifies that numbers is an array of arrays that store integers.

How do you access array of arrays?

In order to access items in a nested array, you would add another index number to correspond to the inner array. In the above example, we accessed the array at position 1 of the nestedArray variable, then the item at position 0 in the inner array.


3 Answers

Afaik, the most simple and keystroke effective way is this to initialize a jagged array is:

double[][] x = new []{new[]{1d, 2d}, new[]{3d, 4.3d}};

Edit:

Actually this works too:

double[][] x = {new[]{1d, 2d}, new[]{3d, 4.3d}};
like image 74
Pop Catalin Avatar answered Oct 19 '22 08:10

Pop Catalin


This should work:

double[][] a = new double[][] 
{ 
    new double[] {1.0d, 2.0d},
    new double[] {3.0d, 4.0d}
};
like image 39
Robert Harvey Avatar answered Oct 19 '22 08:10

Robert Harvey


As you have an array of arrays, you have to create the array objects inside it also:

double[][] a = new double[][] {
  new double[] { 1, 2 },
  new double[] { 3, 4 }
};
like image 3
Guffa Avatar answered Oct 19 '22 09:10

Guffa