首页> C#>如何聚合一个属性,同时求和另一个?

我有一张发票清单,每条记录都包含一个客户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,还是我需要在清单上走一走?

解决方法:

如果你有这样的事情

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)};
上一篇:MongoDB学习笔记(三、MongoDB聚合与更新)


下一篇:MongoDB(七):聚合aggregate