LINQ Sum与GroupBy

时间:2013-08-08 20:40:44

标签: c# linq

(不确定我是否需要GroupBy)

我的(简化)表:

Products(ProductID,Name,Code)
Invoices(InvoiceID,Number,IsPaid)
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()
    });
}

(来自morelinq的DistinctBy方法)

为什么这不完全正确?

编辑

一些数据:

产品 - ProductID = 1,Name = 123,Code = A
产品 - ProductID = 2,Name = 456,Code = A
发票 - InvoiceID = 1,Number = INV123,IsPaid = True
发票_产品 - InvoiceID = 1,ProductID = 1,数量= 10,价格= 100
Invoices_Products - InvoiceID = 1,ProductID = 2,Quantity = 10,Price = 200

预期结果:

代码= A,SalesValue = 3000

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

根据您的描述,我会写:

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

那是你需要的吗?您的代码中的item.A和item.B是什么?