I have 10 1-D arrays, say all of a length of 5. How can I convert them into one larger 2-D array so I only have one 2-D array with 50 cells? I'm not too good with C# so I don't know if there is an easy way to do this, or will I just have to assign each index individually.
Asked
Active
Viewed 381 times
0
-
How do you intend to use this 2-D array? Are you trying to do something like `2dArr[1].[4]`? if so then perhaps you are better off with an `Array of Array` something like `var myArr = new int[][] { arr1, arr2, arr3 ... }` where the `arrX` are `int[]` – Luiso Aug 12 '16 at 20:30
-
Consider using a jagged array. – NPSF3000 Aug 12 '16 at 20:42
-
This Jon Skeet answer is interesting, even if dealing with a bit different use case (you can always convert your separate arrays into a list of arrays as used there): http://stackoverflow.com/a/9775057/172769 – Luc Morin Aug 12 '16 at 20:54
1 Answers
1
//assuming 1-D arrays are setup like so.
int[] array1 = new int[5];
int[] array2 = new int[5];
...
int[] array10 = new int[5];
//Convert to 2-D array:
int[,] newarray = new int[10,5];
for (int i = 0; i < 5; i++) {
newarray[0, i] = array1[i];
newarray[1, i] = array2[i];
newarray[9, i] = array10[i];
}
//using JaggedArrays
int[][] jaggedArray = new int[10][];
jaggedArray[0] = array1;
jaggedArray[1] = array2;
...
jaggedArray[9] = array10;
There's not a really good way to do this with loops since you say you have 10 separate 1-D arrays. You could try converting them all to a single 1-D array and then converting THAT to a 2-D array, but with your current setup this is likely how you'll have to do it.
For converting a single 1-D array to a 2-D array, check out this link:

Community
- 1
- 1

D. Stewart
- 471
- 4
- 15
-
-
-
Getting a `Wrong number of indices inside[]; expected 2` when trying to assign the other arrays into the new one. I have this. `string[,] output = new string[10,10]; output[0] = names;` – Aug 12 '16 at 20:36
-
Edited my answer to show jagged arrays along with standard 2-D arrays. Both of those should work now. – D. Stewart Aug 12 '16 at 20:44