Reputation: 3045
reduced my hundred lines of arrays to 2..
Would love to know if there is a different way of instantiating the array and allow the below code
public [,]ary = new double[,]{
{ 11.4, 11.4, 11.4, 11.4, 11.4, 11.3, 10.9, 17.3, 10.6 },
{ 14.6, 14.6, 14.6, 14.6, 14.6, 14.6, 14.6}
}
Currently I have fixed my issue by adding 0's to the 8th and 9th position in array 2
Or if i absolutely have to type it out
ary[0,1] = [...]
.
.
//Skipping 8th and 9th position in array 2
Upvotes: 0
Views: 45
Reputation: 203821
One option is to write a method to transform a jagged array into a two dimensional array, initialize a jagged array and then convert it. This would result in any array shorter than the max array being padded with the default value, which appears to be what you want.
public static T[,] MakeSquare<T>(this T[][] jagged)
{
int maxWidth = jagged.Max(array => array.Length);
T[,] output = new T[jagged.Length, maxWidth];
for (int i = 0; i < output.GetLength(0); i++)
for (int j = 0; j < output.GetLength(1); j++)
{
output[i, j] = jagged[i][j];
}
return output;
}
now you can write:
double[,] array = new double[][]
{
new[]{ 11.4, 11.4, 11.4, 11.4, 11.4, 11.3, 10.9, 17.3, 10.6 },
new[]{ 14.6, 14.6, 14.6, 14.6, 14.6, 14.6, 14.6}
}.MakeSquare();
Now this method does mean adding some costs at runtime in exchange for the convenience on the programmers side, but if these are arrays that you're defining as literals, they really shouldn't be so big that copying their data to a new array is prohibitively expensive. If there's that much content you shouldn't be defining it as literal data to begin with, but rather putting it in a database or something.
Upvotes: 1