[英]Copy single row from multidimensional array into new one dimensional array
I would like to copy a specific row from a multidimensional array to a new one dimensional array that can be used somewhere else in my code. 我想将特定的行从多维数组复制到新的一维数组,该数组可以在代码的其他地方使用。
Input: 输入:
Multidimensional array[3,3]: 多维数组[3,3]:
33 300 500,
56 354 516,
65 654 489,
Required output: 要求的输出:
Single Dimension Array (second line) 一维数组(第二行)
56 354 516
This is a case where the Buffer.BlockCopy
may come handy: 在这种情况下,
Buffer.BlockCopy
可能会派上用场:
int[,] original = new int[3, 3]
{
{ 33, 300, 500 },
{ 56, 354, 516 },
{ 65, 654, 489 }
};
int[] target = new int[3];
int rowIndex = 1; //get the row you want to extract your data from (start from 0)
int columnNo = original.GetLength(1); //get the number of column
Buffer.BlockCopy(original, rowIndex * columnNo * sizeof(int), target, 0, columnNo * sizeof(int));
You will get in your target
: 您将实现
target
:
56, 354, 516
var source = new int[3, 3]
{
{ 33, 300, 500 },
{ 56, 354, 516 },
{ 65, 654, 489 }
};
// initialize destination array with expected length
var dest = new int[source.GetLength(1)];
// define row number
var rowNumber = 1;
// copy elemements to destination array
for (int i = 0; i < source.GetLength(1); i++)
{
dest[i] = (int) source.GetValue(rowNumber, i);
}
Should be something like this: 应该是这样的:
int[][] arrayComplex = {new[] {33, 300, 500},new []{56, 354, 516}, new []{65, 654, 489}};
int[] arraySingle = new int[3];
for (int i = 0; i < arrayComplex[1].Length; i++)
{
arraySingle[i] = arrayComplex[1][i];
}
foreach (var i in arraySingle)
{
Console.Write(i + " ");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.