Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a list of objects with LINQ

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?

like image 852
Eran Avatar asked Apr 13 '12 09:04

Eran


1 Answers

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()
}
like image 162
Jon Skeet Avatar answered Oct 02 '22 23:10

Jon Skeet