6

(不确定我是否需要 GroupBy)

我的(简化的)表:

Products(ProductID, Name, Code)
Invoices(InvoiceID, Number, IsPaid)
Invoices_Products(InvoiceID, ProductID, Quantity, Price) - 多对多链接表

我需要显示按总和(数量*价格)的产品代码分组的已付款发票的 Invoices_Products 列表。

我首先用来获取可以绑定到 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)

为什么这不正确?

编辑:

一些数据:

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

预期结果:

代码 = A,销售额 = 3000

4

2 回答 2

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()};
于 2013-08-08T21:11:16.307 回答
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 是什么?

于 2013-08-08T20:57:57.270 回答