LinQ to GroupBy objects () by object and total () by total

I have a fairly simple case that I started solving with foreach (), but then I thought I could do it with Linq.

Basically, I have an IList containing PaymentTransaction objects, and there are 2 Dealer and Amount properties.

I want GroupBy() on Dealer and Sum() on Amount .

I tried to execute this using the 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?

+4
source share
3 answers

The question is a bit unclear about what you really want to get the result for, so I assume that you want to sum 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) }); 
+13
source

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

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

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

+2
source

Use group overload , which eliminates the need for choice, accepting a sequence according to its key, thus creating a result value from each group and a key. Then each of the elements is projected:

 GroupBy(pt => pt.Dealer, pt => pt.Amount, (dealer, amount) => new { Dealer = dealer, TotalAmount = amount.Sum() } ) 
+2
source

Source: https://habr.com/ru/post/1305640/


All Articles