c#将一维数组赋值给二维数组语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1099266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:12:22  来源:igfitidea点击:

c# assign 1 dimensional array to 2 dimensional array syntax

c#arraysmultidimensional-array

提问by m3ntat

I want to do something like:

我想做类似的事情:

object[] rowOfObjects = GetRow();//filled somewhere else
object[,] tableOfObjects = new object[10,10];

tableOfObjects[0] = rowOfObjects;

is this somehow possible and what is the syntax?

这是可能的,语法是什么?

or I need to do this:

或者我需要这样做:

for (int i = 0; i < rowOfObjects.Length; i++)
{
   tableOfObjects[0,i] = rowOfObjects[i];
}

and fill up the 2 dimensional arrays row using a loop?

并使用循环填充二维数组行?

Thanks

谢谢

采纳答案by Guffa

No, if you are using a two dimensional array it's not possible. You have to copy each item.

不,如果您使用的是二维数组,则不可能。您必须复制每个项目。

If you use a jagged array, it works just fine:

如果您使用锯齿状数组,它就可以正常工作:

// create array of arrays
object[][] tableOfObject = new object[10][];
// create arrays to put in the array of arrays
for (int i = 0; i < 10; i++) tableOfObject[i] = new object[10];

// get row as array
object[] rowOfObject = GetRow();
// put array in array of arrays
tableOfObjects[0] = rowOfObjects;

If you are getting all the data as rows, you of course don't need the loop that puts arrays in the array of arrays, as you would just replace them anyway.

如果您将所有数据作为行获取,您当然不需要将数组放入数组数组的循环,因为无论如何您都将替换它们。

回答by Justin Drury

So, Something like:

所以,像这样:

    public static object[] GetRow()
    {
        object[,] test = new object[10,10];
        int a = 0;
        object[] row = new object[10];
        for(a = 0; a <= 10; a++)
        {
            row[a] = test[0, a];
        }
        return row;
    }

回答by Justin Drury

if I have gigabyte size arrays, I would do it in C++/CLI playing with pointers and doing just memcpy instead of having gazillion slow boundary-checked array indexing operations.

如果我有千兆字节大小的数组,我会在 C++/CLI 中使用指针进行操作并只执行 memcpy,而不是进行大量缓慢的边界检查数组索引操作。

回答by Matthew Finlay

If your array is an array of value types, it is possible.

如果您的数组是值类型数组,则有可能。

int[,] twoD = new int[2, 2] {
    {0,1},
    {2,3}
};
int[] oneD = new int[2] 
    { 4, 5 };
int destRow = 1;
Buffer.BlockCopy(
    oneD, // src
    0, // srcOffset
    twoD, // dst
    destRow * twoD.GetLength(1) * sizeof(int), // dstOffset
    oneD.Length * sizeof(int)); // count
// twoD now equals
// {0,1},
// {4,5}

It is not possible with an array of objects.

对象数组是不可能的。

Note: Since .net3.5 this will only work with an array of primitives.

注意:从 .net3.5 开始,这只适用于原始数组。