user1146081
user1146081

Reputation: 195

C#: 1d arrays to 2d array

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?

Upvotes: 0

Views: 2112

Answers (4)

furkle
furkle

Reputation: 5059

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.

Upvotes: 1

zam664
zam664

Reputation: 767

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]);
     }
 }

Upvotes: 0

user2160375
user2160375

Reputation:

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

Upvotes: 2

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101680

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.

Upvotes: 1

Related Questions