none
Assign List to Array of List in C# RRS feed

  • Question

  • Hello,

    How can I fix this error?

    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<int> a = new List<int> { 1, 2, 3 };
                List<int> b = new List<int> { 1, 2, 3 , 4};
                List<List<int>> list = new List<List<int>>();
                list[0] = a; //ERROR
                list[1] = b; //ERROR
            }
        }
    }
    

    Saturday, October 26, 2019 5:48 AM

All replies

  • To fix the error, you need to use the "Add" method of the list. Otherwise, it starts with zero entries, so you cannot access the entries at position 0 and 1 (which do not yet exist).

    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<int> a = new List<int> { 1, 2, 3 };
                List<int> b = new List<int> { 1, 2, 3 , 4};
                List<List<int>> list = new List<List<int>>();
                list.Add(a);
                list.Add(b);        }
        }


    Saturday, October 26, 2019 8:35 AM
    Moderator