将多维数组中的单行复制到新的一维数组中

问题描述 投票:0回答:4

我想将多维数组中的特定行复制到一个新的一维数组,该数组可以在我的代码中的其他地方使用。

输入:

多维数组[3,3]:

33 300 500,
56 354 516,
65 654 489,

所需输出:

一维数组(第二行)

56 354 516
c# arrays multidimensional-array
4个回答
4
投票

在这种情况下

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

2
投票
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);
}

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 + "  ");
        }

0
投票

在 .NET Core 2.1 及更高版本中,您可以使用

MemoryMarshal.CreateSpan<T>(T, Int32)
方法从多维数组创建线性跨度。之后使用
Span<T>.CopyTo(Span<T>)
方法复制需要的内容

相反也是可能的:您可以将数据从单维数组复制到多维数组。

int[,] table =
{
    { 33, 300, 500 },
    { 56, 354, 516 },
    { 65, 654, 489 }
};

int[] ints1 = new int[3];
int[] ints2 = [1, 2, 3, 4];

var tableSpan = MemoryMarshal.CreateSpan(ref table[0, 0], table.Length);
// tableSpan is linear here: [33, 300, 500, 56, 354, 516, 65, 654, 489]

tableSpan.Slice(3, ints1.Length).CopyTo(ints1);
// ints1 is now: [56, 354, 516]

ints2.AsSpan().CopyTo(tableSpan.Slice(3, ints2.Length));
// table is now:
// {
//     { 33, 300, 500 },
//     { 1, 2, 3 },
//     { 4, 654, 489 }
// }
© www.soinside.com 2019 - 2024. All rights reserved.