【问题标题】:Fill a list of objects with LINQ使用 LINQ 填充对象列表
【发布时间】:2012-04-13 09:19:56
【问题描述】:

我创建了一个表,并将其插入

var CurrTable;

表格如下所示:

SaleID | ProductID | ProductName

  1    |     1     |    Book
  1    |     2     |  Notebook
  2    |     3     |   Guitar
  2    |     4     |   Piano

我有两个类,ProductInfo 和 SaleInfo:

public class ProductInfo
{
    int ProductID;
    string ProductName;
}

public class SaleInfo
{
    int SaleID;
    List<ProductInfo> products;
}

我只想用数据填写 SaleInfo (List&lt;SaleInfo&gt;) 列表...

我写的查询是这样的:

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();

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

我该怎么做?

【问题讨论】:

    标签: linq entity-framework linq-to-sql linq-to-entities linq-to-objects


    【解决方案1】:

    我怀疑你希望你的选择子句是:

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

    【讨论】:

    • 如果我不想将其具体化到列表中怎么办?如果我想在 IQueryable 中保留 IQueryable 怎么办?这有意义吗?有可能吗?
    • @LuisGouveia:你总是可以不打电话给ToList...但是如果不了解更多关于你的背景,很难说这是否会达到你想要的效果。
    • 上帝保佑你!我整个星期都在努力!现在我可以休息一下了! :D
    【解决方案2】:

    可能是这样的:

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

    如果您应该能够访问您的属性。我会把课程改成这样:

    public class ProductInfo
    {
        public int ProductID;
        public string ProductName;
    }
    
    public class SaleInfo
    {
        public int SaleID;
        public List<ProductInfo> products;
    }
    

    【讨论】:

    • 您知道您是否可以考虑接受这个答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 2012-11-06
    • 2021-09-24
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    相关资源
    最近更新 更多