Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinQ to objects GroupBy() by object and Sum() by amount

I have a pretty simple case which I started solving using foreach(), but then I thought I could do it using Linq.

Basically I have IList that contains PaymentTransaction objects and there are 2 properties Dealer and Amount.

I want to GroupBy() by Dealer and Sum() by Amount.

I tried to accomplish this using following code, but unfortunately it does not work:

var test = paymentTransactionDao.GetAll().GroupBy(x => x.Dealer).Sum(x => x.Amount);

What exactly am I doing wrong here?

like image 724
Daniil Harik Avatar asked Dec 04 '22 13:12

Daniil Harik


1 Answers

The question is a bit unclear on what you really want the result to be, so I assume that you want to sum up the amounts in each group:

var test =
  paymentTransactionDao.GetAll()
  .GroupBy(x => x.Dealer)
  .Select(g => new { Dealer = g.Key, Sum = g.Sum(x => x.Amount) });
like image 166
Guffa Avatar answered Jan 01 '23 01:01

Guffa