views:

2495

answers:

3

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

+3  A: 

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.

Guffa
Thanks so what is the difference between:object[][] tableOfObject = new object[10][10];andobject[,] tableOfObjects = new object[10,10];Many thanks.
m3ntat
An object[,] is a two dimensional array, it is always rectangular (all rows are the same length). An object[][] is a jagged array; an array of object[] arrays. As each row is an array in itself, they don't have to be the same length.
Guffa
Ahh that makes sense. Thanks Guffa.
m3ntat
Keep in mind that jagged arrays have poorer performance and occupy more memory than "2d arrays" (they're actually held in memory as a 1d array). Depending on what your program does, this may matter.
Blindy
A: 

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;
    }
Justin Drury
That's the opposite; getting items from a two dimensional array into a one dimensional array. (Also, an array with the length 10 has index 0-9, not 0-10).
Guffa
whoops, my bad, I didn't actually run the code, I was just doing it from memory.
Justin Drury
+1  A: 

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.

Alex