3

I have a list of invoices and each record consist of a customer ID and an amount. The aim is to produce a list of payments where each payment is unique per customer (there might be multiple invoices per each customer) and sums the related invoices' amounts to a total.

Producing a list of distinct invoices (with respect to the customer ID) is very easy. The things is that I then only have the value of the first invoice's amount and not the sum.

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 smooth LINQ-fu for that or do I need to go foreach on my list?

Community
  • 1
  • 1
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • 7
    It would be a lot easier to help you if you provided sample input and expected output - along with how far you'd got so far. – Jon Skeet Jul 21 '15 at 12:22

2 Answers2

2

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 could have your goal as

var results = from i in invoices
              group i by i.Id into g
              select new { Id = g.Key, TotalAmount = g.Sum(i => i.Amount)};
Juan M. Elosegui
  • 6,471
  • 5
  • 35
  • 48
1

Based on the answer of jmelosegui:

List<Payment> distinct = invoices
   .GroupBy(c => c.CustomerId)
   .Select(c => new Payment
   {
     CustomerId = c.Key, 
     Total = c.Sum(x => x.Amount)
   }).ToList();
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
  • @jmelosegui Awesome, thanks to both. I just realized that it's not going to work, though. The answer to the stated problem itself is valid. Sadly though, I'm getting the error that an instance of entity/complex type *Payment* cannot be constructed in a LINQ to Entities query... I'm assuming that this is an unrelated issue to the original question and needs to be investigated separately. – Konrad Viltersten Jul 21 '15 at 13:52