locked
Initialise List<int?> in Linq to SQL? RRS feed

  • Question

  • User-745958333 posted

    Hi.

    I want to insert a default list in Linq, because I am not yet ready to populate it.  For example, if i have the object:

    public class test()
    {
        public List<int?> testlist { get; set; }
    }

    and in my Linq query i do:

    ....
    select new test
    {
        testlist = new List<int?>()
    }
    

    I get an error about Ling not being able to initialise IEnumerable lists etc.  What would be the best way to do this as part of the Linq query?

    Thanks.

    Thursday, January 21, 2016 10:35 AM

Answers

  • User-271186128 posted

    Hi Captain Planet,

    You could initialize the IEnumerable lists outside the LINQ Query statement. Like this:

                    List<int?> newlist = new List<int?>();
                    var query = (from cc in context.Employees
                                select new Test
                                {
                                    ID = cc.EmployeeID,
                                    testList = newlist
                                }).ToList();

    Best regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 22, 2016 2:08 AM

All replies

  • User1577371250 posted

    Hi,

    you can do like this in the constructor.

    public class test
        {
            public test()
            {
                testlist = new List<int?>();
            }
    public List<int?> testlist { get; set; } }

    Thursday, January 21, 2016 10:49 AM
  • User-745958333 posted

    Thanks for that.  I just wondered if there was a specific Linq way to do it, but if not then this is fine for now.  Thanks.

    Thursday, January 21, 2016 11:50 AM
  • User-271186128 posted

    Hi Captain Planet,

    You could initialize the IEnumerable lists outside the LINQ Query statement. Like this:

                    List<int?> newlist = new List<int?>();
                    var query = (from cc in context.Employees
                                select new Test
                                {
                                    ID = cc.EmployeeID,
                                    testList = newlist
                                }).ToList();

    Best regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 22, 2016 2:08 AM