如何在求和另一个的同时汇总一个 属性?

How to aggregate over one property while summing another?

我有一张发票清单,每条记录都包含一个客户 ID 和一个金额。目的是生成一个付款列表,其中每个客户的每笔付款都是唯一的(每个客户可能有多张发票)并将相关发票的金额相加。

生成不同发票的列表(关于客户 ID)是 very easy。问题是我只有第一张发票金额的价值,而不是总和。

List<Payment> distinct = invoices
  .GroupBy(invoice => invoice.CustomerId)
  .Select(group => group.First())
  .Select(invoice => new Payment
  {
    CustomerId = invoice.CustomerId,
    Total = invoice.Amount
  }).ToList();

是否有流畅的 LINQ-fu 或我需要在我的列表中使用 foreach

如果你有这样的东西

Invoice[] invoices = new Invoice[3];

invoices[0] = new Invoice { Id = 1, Amount = 100 }; 
invoices[1] = new Invoice { Id = 1, Amount = 150 }; 
invoices[2] = new Invoice { Id = 2, Amount = 300 }; 

那么你的目标可以是

var results = from i in invoices
              group i by i.Id into g
              select new { Id = g.Key, TotalAmount = g.Sum(i => i.Amount)};

根据jmelosegui的回答:

List<Payment> distinct = invoices
   .GroupBy(c => c.CustomerId)
   .Select(c => new Payment
   {
     CustomerId = c.Key, 
     Total = c.Sum(x => x.Amount)
   }).ToList();