【问题标题】:LINQ SubqueryLINQ 子查询
【发布时间】:2008-12-09 03:42:10
【问题描述】:

我需要对数据库表中的时间段 (Period) 和表中的发票列表 (Invoice) 执行 LINQ 查询,这些发票位于该期间的开始日期和结束日期内。两个表之间没有key引用,如何进行Invoice子查询?

我正在尝试做类似以下的事情:

var query = (from p in db.DataContext.Periods
             // Subquery i in db.DataContext.Invoices
             let InvoiceAmount = i.Where(t => t.InvoiceDate >= p.StartDate && t.InvoiceDate <= p.EndDate)
             select new PeriodView
             (
                p.Name,
                p.StartDate,
                p.EndDate,
                InvoiceAmount.Count()
              ));

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    var periodViewList = 
        (from p in db.DataContext.Periods
        select new PeriodView(
          p.Name,
          p.StartDate,
          p.EndDate,
          db.DataContext.Invoices.Where(i => i.InvoiceDate >= p.StartDate && i.InvoiceDate <= p.EndDate).Count()
        )).ToList();
    

    我假设 PeriodView 构造函数看起来像这样

    public PeriodView (string name, DateTime startDate, DateTime endDate, int invoiceCount) {
    ...
    }
    

    【讨论】:

    • 为了清楚起见,这将发出 N+1 个查询,其中 N 是周期数。 +1
    猜你喜欢
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多