c# assign 1 dimensional array to 2 dimensional array syntax

前端 未结 4 1578
孤街浪徒
孤街浪徒 2021-02-07 10:10

I want to do something like:

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

tableOfObjects[0] = rowOfObj         


        
相关标签:
4条回答
  • 2021-02-07 10:22

    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;
        }
    
    0 讨论(0)
  • 2021-02-07 10:24

    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.

    0 讨论(0)
  • 2021-02-07 10:27

    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.

    0 讨论(0)
  • 2021-02-07 10:29

    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.

    0 讨论(0)
提交回复
热议问题