Do you always have to start at the index zero when writing a 2D list?

95 views Asked by At

I want to fill in a 2Dlist, but start at the third position [2]. Is this somehow possible? A short code for understanding what i mean:

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

for (int i = 0; i < 5; i++)
{
  List2D[2].Add("i")
}

I get the following error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

EDIT: Any idea how to fill in a 4D list?

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

for (int i = 0; i < List1.Count; i++)
{
    List<List<List<string>>> List3D = new List<List<List<string>>>();
    for (int j = 0; j < List2.Count; j++)
    {
        List<List<string>> List2D = new List<List<string>>();
        for (int k = 0; k < List3.Count; k++)
        {
            List<string> Lijst1D = new List<string>();
            List2D.Add(Lijst1D);
        }
        List3D.Add(List2D);
    }
    List4D.Add(List3D);
}

So later I can call: List4D[2][3][0].Add("test");

1

There are 1 answers

1
Andrey Korneyev On

Since you just created your List2D and not added any nested list into it, you can't access its third element (there is nothing there).

You have to add some items first:

List<List<string>> List2D = new List<List<string>>();
List2D.Add(new List<string>());
List2D.Add(new List<string>());
List2D.Add(new List<string>());

for (int i=0; i<5; i++)
{
  List2D[2].Add("i")
}

Update

Well, core idea of filling that list remains the same: if you want to access List4D[2][3][0] - first you need to fill all of lists in "path".

You can do it something like this:

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

int i1 = 2, i2 = 3, i3 = 0;

for (int i = 0; i <= Math.Max(i1, 1); i++)
    List4D.Add(new List<List<List<string>>>());

for (int i = 0; i <= Math.Max(i2, 1); i++)
    List4D[i1].Add(new List<List<string>>());

for (int i = 0; i <= Math.Max(i3, 1); i++)
    List4D[i1][i2].Add(new List<string>());

List4D[i1][i2][i3].Add("test");

Frankly, idea of 4D list looks a little bit "syntetic". In real application probably it is not the best data structure because of clumsy addressing.