我有一张发票清单,每条记录都包含一个客户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 吗?
答案 0 :(得分:2)
如果你有类似的东西
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)};
答案 1 :(得分:1)
根据jmelosegui的回答:
List<Payment> distinct = invoices
.GroupBy(c => c.CustomerId)
.Select(c => new Payment
{
CustomerId = c.Key,
Total = c.Sum(x => x.Amount)
}).ToList();