15,881,967 members
See more:
When I use C #, encounters a type conversion error. How to double [] [] type into a double [,] type in C #
Posted

## Solution 1

Manually.

This is because the first example is an array of arrays (called a jagged array), whereas the second example is a two dimensional array. The first one can have different elements of different sizes for each entry and the second one has the same number of entries per primary entry.

For example:

C#
double[][] arr1 = new double[2][];
arr1[0] = new double[5];
arr1[1] = new double[3];

There is no way to represent that with a double[,] since the first element has a different size array than the second. You could do double[2,5] but the second element would contain 2 extra values.

This has to be done on a case-by-case basis.

Here, I made a function that will convert a jagged array to a 2 dimensional array:

C#
public double[,] ConvertJagged(double[][] array)
{
int dim1 = array.GetLength(0);
int dim2 = 0;

for (int i = 0; i < dim1; i++)
{
if (array[i].GetLength(0) > dim2)
dim2 = array[i].GetLength(0);
}

double[,] retVal = new double[dim1, dim2];

for (int i = 0; i < dim1; i++)
{
for (int j = 0; j < array[i].GetLength(0); j++)
{
retVal[i, j] = array[i][j];
}
}

return retVal;
}

Or, if you want a generic version:

C#
public T[,] ConvertJagged<T>(T[][] array)
{
int dim1 = array.GetLength(0);
int dim2 = 0;

for (int i = 0; i < dim1; i++)
{
if (array[i].GetLength(0) > dim2)
dim2 = array[i].GetLength(0);
}

T[,] retVal = new T[dim1, dim2];

for (int i = 0; i < dim1; i++)
{
for (int j = 0; j < array[i].GetLength(0); j++)
{
retVal[i, j] = array[i][j];
}
}

return retVal;
}

Call like:

C#
double[][] jagged = new double[5][];
//Initialize jagged
double[,] twoDim = ConvertJagged(jagged);   //Non-generic version
double[,] twoDim2 = ConvertJagged<double>(jagged);  //Generic version

It will make a new 2 dimensional array with the biggest jagged dimensions and return an array that matches. It shouldn't care that one of the jagged elements is not the same size as the other ones, the additional entries will be 0.0.

The generic version will convert any type of jagged array.

v4

## Solution 2

For double [] [], if the second dimension is the same, to have a simple way to turn into a double [,]? Or that I can use for loop assignment (of course, the second dimension is the same)?