-2

I have a payment class similar to the following

class Payment
{
    public int ContactId {get; set;}
    public DateTime Date {get; set;}
    public decimal Amount {get; set;}
}

In a payment list, I would like to sum the Amount field for the rows that have the same value in the ContactId field and then in the Data field.

Here is an example:

List<Payment> payments;
Payment payment;
payment = new Payment
{
    ContactId = 1,
    Date = DateTime.Parse("01/01/2018"),
    Amount = 1m
}
payments.Add(payment);

payment = new Payment
{
    ContactId = 1,
    Date = DateTime.Parse("01/01/2018"),
    Amount = 1m
}
payments.Add(payment);

payment = new Payment
{
    ContactId = 2,
    Date = DateTime.Parse("01/01/2018"),
    Amount = 1m
}
payments.Add(payment);

So I have a list of three elements.

I look for a solution that in this case gives me back a list consisting of two rows.

Row 1: ContactId=1; Date="01/01/2018"; Amount=2;

Row 2: ContactId=2; Date="01/01/2018"; Amount=1;

woller
  • 71
  • 2
  • 7

1 Answers1

3

So you want to group by ContactId and the Date and get the sum of Amount?

Easiest approach is using LINQ:

IEnumerable<Payment> contactDateGroups = payments
   .GroupBy(x => new { x.ContactId, x.Date.Date })
   .Select(g => new Payment{ 
        ContactId = g.Key.ContactId,
        Date = g.Key.Date,
        Amount = g.Sum(x => x.Amount)
    });
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939