带有GroupBy的LINQ求和

本文关键字:求和 LINQ GroupBy 带有 | 更新日期: 2023-09-27 18:26:52

(不确定是否需要GroupBy)

我的(简化)表格:

Products(产品ID、名称、代码)
Invoices(InvoiceID,Number,IsPayed)
Invoices_Products(InvoiceID,ProductID,Quantity,Price)-多对多链接表

我需要显示一个按产品代码分组的已付款发票的发票_产品列表,该产品代码总计(数量*价格)。

我第一次用来获得可以绑定到UI的集合的代码:

IEnumerable<Invoices_Products> invoices_products = db.Invoices_Products
.Where(ip => ip.Invoice.IsPaid).DistinctBy(m => m.Product.Code);

然后,我对其进行迭代,将其绑定到UI:

List<BindableInvoiceProduct> bindableInvoiceProducts = 
new List<BindableInvoiceProduct>();
foreach (var item in invoices_products)
{
    decimal salesValue = db.Invoices_Products.Where(ip => ip.Invoice.IsPaid 
    && ip.Product.Code == item.Product.Code).Sum(m => (m.Price * m.Quantity));
    bindableInvoiceProducts.Add(new BindableInvoiceProduct()
    {
        A = item.A,
        B = item.B,
        SalesValue = salesValue.ToString()
    });
}

DistinctBy方法来自morelinq)

为什么总的来说不正确?

编辑:

一些数据:

产品-产品ID=1,名称=123,代码=A
产品-产品ID=2,名称=456,代码=A
发票-InvoiceID=1,Number=INV123,IsPayed=True
Invoices_Products-InvoiceID=1,ProductID=1,数量=10,价格=100
Invoices_Products-InvoiceID=1,ProductID=2,数量=10,价格=200

预期结果:

代码=A,销售价值=3000

带有GroupBy的LINQ求和

from invoice in invoices
where invoice.IsPaid
from xr in invoice.InvoiceProducts
group xr.Quantity * xr.Price by xr.Product.Code into g
select new {Code = g.Key, SalesValue = g.Sum()};

如果你想要每张发票,那么:

from invoice in invoices
where invoice.IsPaid
from xr in invoice.InvoiceProducts
group xr.Quantity * xr.Price
  by new {Code = xr.Product.Code, Invoice = invoice }
  into g
select new {
  Code = g.Key.Code,
  Invoice = g.Key.Invoice,
  SalesValue = g.Sum()};

根据你的描述,我会写:

var bindableInvoiceProducts = db.Invoices_Products
    .Where(ip => ip.Invoice.IsPaid)
    .GroupBy(ip => ip.Product.Code, 
             (code, ips) => new BindableInvoiceProduct()
                {
                    Code = code,
                    SalesValue = ips.Sum(ip => (ip.Price*ip.Quantity))
                })
    .ToList();

这是你需要的吗?什么是项目。A和项目。你的代码里有B?