Reputation: 1
From a previous assignment we had 4 arrays:
string[] titles = new string[10];
string[] authors = new string[10];
string[] publishers = new string[10];
string[] dates = new string[10];
In this assignment we have to convert all of these into a single 2D array. I understand how to declare a 2D array (e.g. int[,] items = new int[4, 6];
), but as to putting 4 arrays into a single 2D array has got me completely stumped. Any help greatly appreciated.
Upvotes: 0
Views: 309
Reputation: 494
In case you need a 2D array specifically for academic purposes. Please note you should use jagged arrays instead (See notes at the end!)
string[] titles = new string[10];
string[] authors = new string[10];
string[] publishers = new string[10];
string[] dates = new string[10];
string[,] array2D = new string[4, 10];
for (int i = 0; i < 4; i++)
{
string[] myCurrentArray = new string[] { };
switch (i)
{
case 0:
myCurrentArray = titles;
break;
case 1:
myCurrentArray = authors;
break;
case 2:
myCurrentArray = publishers;
break;
case 3:
myCurrentArray = dates;
break;
default:
break;
}
for (int j = 0; j < 10; j++)
{
array2D[i, j] = myCurrentArray[j];
Console.WriteLine("Array [" + i + "][" + j + "]: " + array2D[i, j]);
}
}
A brief explanation, what you have to do is fill your multi-dimensional magic contraption manually. In order to retrieve those values you'll be invoking a lot, which is really slow. The most efficient way to do this, given you already have the arrays filled with data is selecting those 4 arrays dynamically and looping through them to retrieve the data and insert it into the 2D array.
The first loop cycles through all 4 arrays, and instances each of them to avoid repeating code later on, the switch handles that. The second loop cycles through each array and retrieves the data to store it properly.
I assume you already know how loops work, nevertherless I'm going to explicitly point out PLEASE BE CAREFUL WITH ARRAY BOUNDS. If you try to reuse this code for arrays with different sizes you will probably run into Array out of bounds Exception
, so please adapt the code accordingly, use Array.Length
for you loop upper bounds, etc. if needed.
This is what you should do (using jagged arrays):
string[] titles = new string[10];
string[] authors = new string[10];
string[] publishers = new string[10];
string[] dates = new string[10];
string[][] table = new string[][] { titles, authors, publishers, dates };
table
will contain all 4 arrays in a single variable.
PLEASE READ THIS There's no reason to use multi-dimensional arrays over jagged arrays, they are slower, they don't accept the object types you already have (string arrays) and will force you to iterate through and fill the data with a couple of nested for loops.
Please check this for info about jagged vs multi-dimensional arrays and understand the differences: What are the differences between a multidimensional array and an array of arrays in C#?
Upvotes: 3