在单个LINQ查询中按父表对多个子表进行分组

时间:2017-11-21 14:30:59

标签: c# linq

我有以下表格和它们之间的关系。我需要结果如下: InvoiceId,(由某个分隔符加入的发票的工作说明),(由PaymentMethod完成的金额总和=该发票的'ABC')。

如何在单个LINQ查询语法(不是表达式/方法语法)中实现此目的?

更新:请注意,InvoicePayment和InvoiceWorkDescription表中的数据可以为空(创建发票但尚未捕获详细信息的情况)。

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

var result = 
   from invoice in invoices
   join workDescription in invoiceWorkDescription 
       on invoice.Id equals workDescription.InvoiceId into workDescriptions
   join payment in invoicePayments
       on invoice.Id equals payment.InvoiceId into payments
   select new {
        InvoiceId = invoice.InvoiceId,
        Descriptions = string.Join(", ", workDescriptions.Select(wd => Description),
        TotalPayments = payment.Where(p => p.PaymentMethod == "ABC").Sum(p => p.Amount) }