Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting List<T> to Array (multidimensional) [duplicate]

Possible Duplicate:
How can I convert a list<> to a multi-dimensional array?

I want to have an array in form of double[,] for this purpose since I do not know what will be the length of this array, I want to make a List first then later using List<T>.ToArray() convert it to double[,]:

public double[,] FilterClampedData(double[,] data)
{
    var finalData = new List<double[]>();

    //Do some stuff on parameter

    return finalData.ToArray(); ///Does not compile :(
}
like image 331
Saeid Yazdani Avatar asked Jul 02 '12 14:07

Saeid Yazdani


2 Answers

Since ToArray returns a one-dimensional array, there is no wonder why this does not compile. If you were returning double[][], it would compile, however. You could also build your 2-D array manually with two nested loops:

var R = finalData.Count;
var C = finalData[0].Length;
var res = new double[R, C];
for (int r = 0 ; r != R ; r++)
    for (int c = 0 ; c != C ; c++)
        res[r, c] = finalData[r][c];
return res;

The code above assumes that you have at least one item in the finalData, and that the length of all lists inside finalData is the same.

like image 192
Sergey Kalinichenko Avatar answered Oct 23 '22 10:10

Sergey Kalinichenko


  1. Instantiate a new double array with the largest size [length of the list, largest array length in the list]
  2. Walk through the list with double for cycle (first on the list, the nested on the current list item) and fill the new array
like image 1
Peter Kiss Avatar answered Oct 23 '22 10:10

Peter Kiss