C#动态多维数组 [英] C# Dynamic multidimensional array

查看:197
本文介绍了C#动态多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能...

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.

}

但是'double [,]'不是动态的,我也不知道数组的最终大小是多少.我可以从中创建一个列表,然后将新行添加到列表中,但随后似乎无法将其转换回double [,]. List.ToArray()要输出一个锯齿状的数组(double [] []).这不会工作.我正在使用LabVIEW开发的程序进行交互,LV拒绝接受锯齿状的数组. LV对固定数组([,])感到满意.

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 ([,]).

有帮助吗?

推荐答案

您可以尝试以下方法:

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;
}

它显式地将高阶维加1,并验证低阶维的长度等于dataToAdd数组.从dataToAdd到2D数组的复制比通过for循环更聪明.无法将Array.Copy应用于不同排名的数组.

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.

这篇关于C#动态多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆