使用 LINQ 填充对象列表

Era*_*ran 5 linq linq-to-objects linq-to-entities entity-framework linq-to-sql

我有一个我创建的表,我将它插入到

var CurrTable;
Run Code Online (Sandbox Code Playgroud)

该表如下所示:

SaleID | ProductID | ProductName

  1    |     1     |    Book
  1    |     2     |  Notebook
  2    |     3     |   Guitar
  2    |     4     |   Piano
Run Code Online (Sandbox Code Playgroud)

我有两个类,ProductInfo 和 SaleInfo:

public class ProductInfo
{
    int ProductID;
    string ProductName;
}

public class SaleInfo
{
    int SaleID;
    List<ProductInfo> products;
}
Run Code Online (Sandbox Code Playgroud)

我只想List<SaleInfo>用数据填充 SaleInfo ( )列表...

我写的查询如下所示:

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();
Run Code Online (Sandbox Code Playgroud)

但是不知道在里面写什么(*...*)。我不想再做一次选择,因为我已经有了数据。我只想在产品列表中填充列表,这就是我使用组功能的原因。

我怎样才能做到这一点?

Jon*_*eet 5

我怀疑你希望你的 select 子句是:

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