Linq查询从表中求和值

时间:2013-05-17 11:48:14

标签: c# linq entity-framework linq-to-sql

我有一个LINQ查询,它接收发票,查找附加的每个项目的数量和单价,并在另一个链接表中查找针对发票的任何付款。

目前这是:

from i in Invoices
select new
{
i.InvoiceId, i.CustomerName,
Items =
    from it in InvoiceItems
    where i.InvoiceId == it.InvoiceId 
    select new { 
    it.Item, 
    it.Quantity, 
    it.UnitPrice,
    SubPrice=it.Quantity*it.UnitPrice
    },
Payments = 
    from pi in PaymentInvoices
    where i.InvoiceId == pi.InvoiceId 
    select new {
    SumPayments=pi.AmountAllocated
    }
}

这显示以下结果:

screenshot of results

如何更改此LINQ查询以仅显示SubPrice和SumPayments的总和(即:

  

发票11:SubPrice = 90.00 SumPayments = 24.00

     

发票12:SubPrice = 175.00,SumPayments = 175.00

感谢您的帮助,

标记

更新显示KENNETH回答后的工作

from i in Invoices
select new
{
    InvoiceID = i.InvoiceId, 
    CustomerName = i.CustomerName,
    SubPrice = InvoiceItems.Where(it => it.InvoiceId == i.InvoiceId).Select(it => it.Quantity*it.UnitPrice).Sum(),
    SumPayments = PaymentInvoices.Where(pi => pi.InvoiceId == i.InvoiceId).Select(pi => pi.AmountAllocated).Sum()
}

1 个答案:

答案 0 :(得分:3)

您可以使用以下方法:

from i in Invoices
select new
{
    InvoiceID = i.InvoiceId, 
    CustomerName = i.CustomerName,
    SubPrice = InvoiceItems.Where(it => it.InvoiceID = i.InvoiceID).Select(it => it.Quantity*it.UnitPrice).Sum(),
    SumPayments = PaymentInvoice.Where(pi => pi.InvoiceId = i.InvoiceId).Select(pi => pi.AmountAllocated).Sum()
}