Search code examples
c#listfor-loopdimensions

Why cant I refer to a random index in my 4D list, while I know it exists?


I got a 4D list, and I want where I want to display only the [k][3][j][z], but this isnt working. I checked all the counts and they are all 5+, so 3[4] should work...

for (int k = 0; k < lijst4D.Count; k++)
{
    for (int i = 0; i < lijst4D[k].Count; i++) // This count is higher than 4!
    {
        for (int j = 0; j < lijst4D[k][i].Count; j++)
        {
            for (int z = 0; z < lijst4D[k][i][j].Count; z++)
            {
                Console.WriteLine(lijst4D[k][i][j][z]); // This is working
                Console.WriteLine(lijst4D[k][3][j][z]); // This is NOT working
            }
        }
    }
}

This isnt working either:

Console.WriteLine(lijst4D[0][0][0][0]);
Console.WriteLine(lijst4D[1][1][1][1]);

Why isnt this working? Can anyone explain me? Am I missing something?

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

EDIT: this IS working tho.. why?

for (int k = 0; k < lijst4D.Count; k++)
{
    for (int i = 3; i < 4; i++) // Will do this loop once
    {
        for (int j = 0; j < lijst4D[k][i].Count; j++)
        {
            for (int z = 0; z < lijst4D[k][i][j].Count; z++)
            {
                Console.WriteLine(lijst4D[k][i][j][z]); 
            }
        }
    }
}

EDIT2: How I fill up my lists:

for (int g = 0; g < List.Count; g++)
{
    List<List<List<string>>> Lijst3D = new List<List<List<string>>>();
    for (int j = 0; j < Alist.Count; j++)
    {
        List<List<string>> Lijst2D = new List<List<string>>();
        for (int k = 0; k < Anotherlist.Count; k++)
        {
            List<string> Lijst1D = new List<string>();
            Lijst2D.Add(Lijst1D);
        }
        Lijst3D.Add(Lijst2D);
    }
    Lijst4D.Add(Lijst3D);
}

Thanks in advance


Solution

  • Based on your code where you're filling your 4D list:

    List<string> Lijst1D = new List<string>();
    Lijst2D.Add(Lijst1D);
    

    Here you're creating new List<string> and adding it to parent 2D list.

    But Lijst1D itself doesn't contains any elements (you haven't added anything to it), so Lijst4D[0] will throw that IndexOutOfRangeException as well as Lijst4D[0][0][0][0] throws it.