Can i convert a list with objects to a two dimensional array

I don't know if this is possible in C #, but it would be great if it was. I have a list of objects that is very easy to convert to an array with the code below:

object [] myArray = wrd.ToArray();

      

It works great, but how do I convert a list with objects to a two dimensional array, where the elements from index 0 to 20 in the list will be on the first line in the two dimensional array. The elements from index 21 through 41 in the list must be on the second line in a two-dimensional array. The elements from index 42 to 62 in the list must be on the third line in the 2D array, and so on. In other words, there should be 20 elements per row, plus 21 rows and 21 columns. For a labyrint image , the character "B" must be reached with index [1,0]

But again I don't know if this is possible, but hopefully a very experienced person can help me.

+3


source to share


1 answer


You can just loop over the array and put the items in 2d.

// Pseudo code...
x = 0
y = 0
loop while i < originalArray.Length

    2dArray[x,y] = originalArray[i]
    i++
    y++

    if y >= 2dArrayRowLength
        x++
        y=0

end loop

      

But really, why bother. 2D arrays in C # don't actually change anything about how data is stored, they're just syntactic suger to access a one-dimensional array in a slightly different way. Just compute the x and y offsets on the fly as you access your one-dimensional array.



Something like that.

object[] data = new object[100];

int xLength = 21;
int yLength = 21;
for (int x = 0; x < xLength; x++)
{
    for (int y = 0; y < yLength; y++)
    {
        var theValue = data[(yLength * x) + y];
        Console.Write(theValue);
    }

    Console.WriteLine();
}

      

0


source







All Articles