Fill a list of objects with LINQ

entity-framework, linq, linq-to-entities, linq-to-objects, linq-to-sql

Solution

I suspect you want your select clause to be:

select new SaleInfo
{
    SaleID = g.Key.SaleId,
    Products = g.Select(x => new ProductInfo { ProductID = x.ProductID,
                                               ProductName = x.ProductName })
                .ToList()
}

Problem

I have a table which I created, and I inserted it to ``` var CurrTable; ``` The table looks like this: ``` SaleID | ProductID | ProductName 1 | 1 | Book 1 | 2 | Notebook 2 | 3 | Guitar 2 | 4 | Piano ``` I have two classes, ProductInfo and SaleInfo: ``` public class ProductInfo { int ProductID; string ProductName; } public class SaleInfo { int SaleID; List<ProductInfo> products; } ``` I just want to fill a list of SaleInfo (`List<SaleInfo>`) with the data... The query I wrote looks like this: ``` List<SaleInfo> results = (from s in CurrTable.AsEnumerable() group s by new { s.SaleId} into g select new SaleInfo { SaleID = g.Key.SaleId, Products = (*...*) }).ToList(); ``` But I don't know what to write in the `(*...*)`. I don't want to do another select, because I already have the data. I just want to fill the list inside the list of products, and that's the reason I used the group function. How can I do this?

Original source