我想将多维数组中的特定行复制到可以在我的代码中的其他位置使用的新的一维数组。
输入:
多维数组[3,3]:
33 300 500,
56 354 516,
65 654 489,
必需的输出:
单维数组(第二行)
56 354 516
答案 0 :(得分:2)
这是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));
您将进入target
:
56, 354, 516
答案 1 :(得分:1)
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);
}
答案 2 :(得分:1)
应该是这样的:
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 + " ");
}