How do I aggregate over one property while summing another?

I have a list of invoices and each record consists of a customer ID and an amount. The goal is to compile a list of payments in which each payment is unique for each customer (there can be multiple invoices for each customer) and sums up the amounts of related invoices in total.

Creating a list of individual invoices (in relation to customer ID) is very easy . The fact is that then I only have the value of the first invoice amount, not the amount.

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

      

Is there a slick LINQ-fu for this or do I need to traverse foreach to my list?

+3


source to share


2 answers


If you have something like this

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 }; 

      



Then you can have your goal like

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

      

+2


source


Building on jmelosegui's answer:



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

      

+1


source







All Articles