Gareth
Gareth

Reputation: 5243

LINQ Selecting a List within a List

I'm trying to fill a list within a list using LINQ to query my database.

The issue I'm facing is that I'm unsure how to select the data into the child list.

When trying to execute the code below, I receive the error

Error 1 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

The model classes are like so:

public class _LayoutViewModel
{
    public List<CallGuideMenuL1> CGL1 { get; set; }
}

public class CallGuideMenuL1
{
    public string Area { get; set; }
    public List<CallGuideMenuL2> Products { get; set; }
}

public class CallGuideMenuL2
{
    public int CallGuideProductId { get; set; }
    public string Product { get; set; }
}

And the DB context:

public class CallGuideArea
{
    public int CallGuideAreaId { get; set; }
    public string Area { get; set; }
    public List<CallGuideProduct> CallGuideProducts { get; set; }
}

public class CallGuideProduct
{
    public int CallGuideProductId { get; set; }
    public string Product { get; set; }
    public int CallGuideAreaId { get; set; }
    public DateTime Added { get; set; }
    public DateTime? Deleted { get; set; }
}

In my controller I'm trying to select the data like so:

_LayoutViewModel vm = new _LayoutViewModel();

vm.CGL1 = from a in db.CallGuideArea
            .SelectMany(p => p.CallGuideProducts)
            select a;

I'm pretty sure it's the select a; line that's the issue as I need to assign the data back to the properties of both CallGuideMenuL1 and CallGuideMenuL2.

Could anyone point me in the right direction around the right LINQ expression?

Upvotes: 1

Views: 2814

Answers (2)

Rodrigo Juarez
Rodrigo Juarez

Reputation: 1785

vm.CGL1 = db.CallGuideArea.Select(a => new CallGuideMenuL1()
{
    Area = a.Area,
    Products = a.CallGuideProducts.Select(p => new CallGuideMenuL2()
    {
        CallGuideProductId = p.CallGuideProductId,
        Product = p.Product
    }).ToList()
}).ToList();

Upvotes: 3

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

Probably vm.CGL1 is declared as List so you need to select into List:

vm.CGL1 = (from a in db.CallGuideArea
            .SelectMany(p => p.CallGuideProducts)
            select a).ToList();

or you will need to project:

vm.CGL1 = (from a in db.CallGuideArea
            .SelectMany(p => p.CallGuideProducts)
            select new CallGuideMenuL1()
            {
               Area = a.--some property
               ...
            }).ToList();

Upvotes: 0

Related Questions