Search code examples
c#arrayslistinitialization

How can I start initialization of "List of list" with columns


I have a list of list and I want to add values column oriented. Like in the following code sample:

Data = new List<List<double>>();
for (int i = 0; i < columnCount; i++)
        {
            for (int j = 0; j < rowCount; j++)
            {
                Data[j][i] = (probabilityList[j]) * K); // It won't work
            }
        }

I know it won't work because Data's index does not exist at current situation, and I need to use add() method.

However, I need to add values to list starts with columns:

[1   , null] ----> [1, null]
[null, null]       [2, null]

How can I add values to a list of list starts with columns?


Solution

  • You need to create actual lists that you place inside your outer list of lists:

    for (int i = 0; i < rowCount; i++)
    {
        Data.Add(new List<double>());
    }
    

    Once you've created all of the inner lists you can go through them and add values to them:

    for (int i = 0; i < columnCount; i++)
    {
        for (int j = 0; j < rowCount; j++)
        {
            Data[j].Add((probabilityList[j]) * K);
        }
    }