views:

372

answers:

2

Hello,

I have 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() bv 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);

Want exactly I'm doing wrong here?

I'm sorry if this question is too simple.

Thank You

A: 

GroupBy will return a bunch of IGrouping<string, PaymentTransaction> (assuming Dealer is a string). Try this:

...GroupBy(...).Select(x => new {Dealer=x.Key, Amount=x.Sum(xx => xx.Amount)});

(Just guessing, as I'm not in front of VS.)

Marcelo Cantos
+2  A: 

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) });
Guffa
Do you need the `GetAll`?
Gabe
Thank You, this works!
Daniil Harik
@gabe: I don't know, I don't assume anything about what kind of object that is or what the method does other than that is returns a collection.
Guffa