假设你有一个像这样的数组:
double[,] rectArray = new double[10,3];
Run Code Online (Sandbox Code Playgroud)
现在你想把第四行作为一个包含3个元素的double []数组而不做:
double[] fourthRow = new double[]{rectArray[3,0],
rectArray[3,1],
rectArray[3,2]};
Run Code Online (Sandbox Code Playgroud)
有可能吗?即使使用Marshal.Something方法?
谢谢!
max*_*max 18
你可以使用Buffer.BlockCopy方法:
const int d1 = 10;
const int d2 = 3;
const int doubleSize = 8;
double[,] rectArray = new double[d1, d2];
double[] target = new double[d2];
int rowToGet = 3;
Buffer.BlockCopy(rectArray, doubleSize * d2 * rowToGet, target, 0, doubleSize * d2);
Run Code Online (Sandbox Code Playgroud)
cod*_*ife 14
LINQ救援:
var s = rectArray.Cast<double>().Skip(9).Take(3).ToArray();
Run Code Online (Sandbox Code Playgroud)
说明:转换多维数组会将其展平为一维数组.之后,我们需要做的就是跳到我们想要的元素(二维数组中的第四个元素解析为Skip(9)...)并从中获取3个元素).
为什么不制作通用的扩展方法?
public static T[] GetRow<T>(this T[,] input2DArray, int row) where T : IComparable
{
var width = input2DArray.GetLength(0);
var height = input2DArray.GetLength(1);
if (row >= height)
throw new IndexOutOfRangeException("Row Index Out of Range");
// Ensures the row requested is within the range of the 2-d array
var returnRow = new T[width];
for(var i = 0; i < width; i++)
returnRow[i] = input2DArray[i, row];
return returnRow;
}
Run Code Online (Sandbox Code Playgroud)
像这样你需要编码的是:
array2D = new double[,];
// ... fill array here
var row = array2D.GetRow(4) // Implies getting 5th row of the 2-D Array
Run Code Online (Sandbox Code Playgroud)
如果您在获取行之后尝试链接方法,并且对LINQ命令也有帮助,这将非常有用.
您可能想使用锯齿状数组。这不是一个 10 x 3 的数组,而是一个数组的数组。
就像是 :
double[][] rectArray;
....
double [] rowArray = rectArray[3];
Run Code Online (Sandbox Code Playgroud)
有很多地方可以了解有关锯齿状数组的更多信息。例如动态创建锯齿状矩形阵列
| 归档时间: |
|
| 查看次数: |
24383 次 |
| 最近记录: |