14,299,779 members
Rate this:
See more:
When I use C #, encounters a type conversion error. How to double [] [] type into a double [,] type in C #
Posted

Rate this:

## 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:

```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:

```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:

```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:

```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.

Its untested so tread lightly.
v4
Rate this:

## 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)?
Ron Beyer 9-Jan-14 21:38pm

Please use the "have a question or comment" button under my solution to direct a question at me. Don't post questions or clarifications as solutions. I updated my answer to show how to do it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 200 Richard MacCutchan 195 Maciej Los 155 CPallini 150 MadMyche 135

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100