0

I have three 1D string arrays A, B and C, 20 elements each.

I'd like to create one 2D[2,19] array D consisted of these 1D arras A, B and C.

I thought I can do like that:

D[0,]=A;
D[1,]=B;
D[2,]=C;

But VS gives me syntax error. How I can do it without iterating over?

user1146081
  • 195
  • 15

4 Answers4

2

There is a difference between multidimensial and jagged arrays. You have used multidimensial, but you are assigning like a jagged array.

So:

TElement[] A = //
TElement[] B = //
TElement[] C = //

var D = new TElement[3][];
D[0] = A;
D[1] = B;
D[2] = C;

Accessing element:

var elem = D[0][10];

More on: http://forums.asp.net/t/1278141.aspx?arrays+multidimensional+versus+jagged

1

You need to use a loop and set each element one by one:

for(int i = 0; i < 20; i++)
{
   D[0, i] = A[i];
   D[1, i] = B[i];
   D[2, i] = C[i];
}

D should be at least [3,20] to hold these values.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

If you want to do this without a for loop, like Selman22 suggested, your other option would be to use a jagged array, or an array of arrays. This is done like so:

int[][] jaggedArray = new int[3][];

jaggedArray[0] = A[i];
jaggedArray[1] = B[i];
jaggedArray[2] = C[i];

These can be accessed with two brackets, e.g. jaggedArray[i][j].

Note that concepts like Length work very differently for jagged arrays as compared to multidimensional arrays. I'd recommend looking over the MSDN documentation here: http://msdn.microsoft.com/en-us/library/2s05feca.aspx

If you want to use List instead, (as you probably should - List is better for almost all use cases in .NET) you can use List< List< T>>, which can be accessed in same fashion as the jagged array.

furkle
  • 5,019
  • 1
  • 15
  • 24
  • Why should use List? If there is no need to add new elements - List is not neccessary - it holds an array under the cover.. –  Oct 29 '14 at 19:34
  • Because Lists have a good deal more function, and very little performance hit. Smarter men than I tell it here: http://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which – furkle Oct 29 '14 at 19:35
0

Do an array of arrays:

 string[] a = new string[3] {"A","B","C"};
 string[] b = new string[3] { "D", "E", "F" };
 string[] c = new string[3] { "G", "H", "I" };
 string[][] d = new string[3][];
 d[0] = a;
 d[1] = b;
 d[2] = c;
 for (int i = 0; i < d.Length; i++) {
     for (int j = 0; j < d[i].Length; j++) {
         MessageBox.Show(d[i][j]);
     }
 }
zam664
  • 757
  • 1
  • 7
  • 18