Assigning members of a list of list to a 2D array in C#

67 Views Asked by At

I create a list of list:

        List<List<string>> C = new List<List<string>>();

Then assign some values to it. Assume the assignment is as follows:

            List<string> B = new List<string>();
            for (int j = 0; j < x; j++)
            {
                B.Clear();
                for (int i = 0; i < y; i++)
                    B.Add(i.ToString());           
                C.Add(B);
             }

x and y vary at each run of the code. So, I do not know them beforehand. (At this point of the code, I do not know how to find the size of C. I mean x and y, not x*y.)

I would like to assign/copy C to a 2D array, D[,]. Before the declaration of D, size of D (i.e., rows and columns that correspond to x and y) should have been calculated in some way by using C. How can I make the assignment?

3

There are 3 best solutions below

0
Vadim Martynov On BEST ANSWER

You can't just assign a jagged array value to a 2D array because these structures store data differently. A jagged array is an array each element of which stores a reference to another array, while a two-dimensional array is a series of elements stored in memory. See also "Multidimensional Arrays (C# Programming Guide)" article.

A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.

Also, you cannot simply assign the value of a list of lists to a variable of two-dimensional array or jagged array type, because these are different data types that require an explicit conversion.

So you need to copy each element to the new array.

List<List<string>> C = FillListWithSomeValues();

int numRows = C.Count;
int numCols = C[0].Count;

string[,] D = new string[numRows, numCols];

for (int row = 0; row < numRows; row++)
    for (int col = 0; col < numCols; col++) 
        D[row, col] = C[row][col];
1
Victorio Gilistro On

You must, first of all, asign values to x and y and declare and initialize b before. Then assign the value of C to D. At least thats one way to do it.

Good luck!

0
Rufus L On

You can find the length of the longest list for the 2D array definition:

int longDimension = C.Max(list => list.Count);