如何对一个属性进行聚合,同时对另一个属性进行求和

本文关键字:属性 求和 另一个 一个 | 更新日期: 2023-09-27 18:03:42

我有一个发票列表,每个记录由客户ID和金额组成。目的是生成一个付款列表,其中每个客户的每个付款都是唯一的(每个客户可能有多个发票),并将相关发票的金额相加为总额。

生成不同发票的列表(相对于客户ID)非常容易。问题是,我只有第一张发票的金额,而不是总额。

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,或者我需要去每个在我的列表?

如何对一个属性进行聚合,同时对另一个属性进行求和

如果你有这样的东西

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