C# Dynamic multidimensional array

百般思念 提交于 2019-12-01 10:35:27

问题


I have a function...

private double[,] AddToArray(double[,] array, double[] dataToAdd)
{
    // Make a new row at the end of 'array' and copy values 
    // from 'dataToAdd' into the new row.
    //
    // Return the new, modified array.

}

However 'double[,]' isn't dynamic and I dont know what the final size of the array will be. I can create a List from it and add the new row to the list, but then I cant seem to convert it back to a double[,]. The List.ToArray() wants to output a jagged array (double[][]). This wont work. I'm interfacing with a program developed in LabVIEW and LV refuses to accept a jagged array. LV is happy with a fixed array ([,]).

Any help?


回答1:


You could try this:

private double[,] AddToArray(double[,] array, double[] dataToAdd)
{
  var dim0 = array.GetLength(0);
  var dim1 = array.GetLength(1);
  if (dim1 != dataToAdd.Length) throw new ArgumentException();

  var na = new double[dim0 + 1, dim1];
  Array.Copy(array, na, array.Length);
  for (var i = 0; i < dim1; ++i) na[dim0, i] = dataToAdd[i];

  return na;
}

It explicitly increments the high-order dimension by one, and also verifies that the length of the low-order dimension is equal to the dataToAdd array. I have not been able to any smarter copying from dataToAdd to the 2D array than by a for loop; it is not possible to apply Array.Copy for different ranked arrays.




回答2:


You could always create the 2-dimensional array manually:

double[,] array = new double[list.Count, data.Length];
for(int i = 0;i < list.Count;++i)
    for(int j = 0;j < data.Length;++j)
        array[i, j] = list[i][j];

That is, of course, assuming that all of the 'dataToAdd' is of uniform length. Otherwise, what do you fill in the array for unused elements?



来源:https://stackoverflow.com/questions/10934453/c-sharp-dynamic-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!