I would like to populate a given dimension of a multidimensional array from a LINQ select.
A loop would be an obvious way but I’d like a “best practise” suggestion.
For instance what the best way to insert this:
this.Facts.Select(f =>f.FactIc).ToArray()
which would return an array of longs into the second dimension of this array:
long[,] vals = new long[1, factCount];
What about an array of arrays? If you find that you quite often need to replace the contents of 1 entire row then maybe each row should be an array in itself. You could even define your own class that contains the row data and then define an array of that class.
BTW, why do you have ToList() and ToArray()?
Edit: Assuming that the result must be a 2D array I would just use the version of foreach below:
Define ForEach like this (this is my favourite extension method):
Then just do
You can’t really get much more efficient than this. The data is not in a flat array to start with so in some way you need to iterate each item and copy the data. This avoids making intermediate copies of the array etc.