Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda for summing shorthand

Tags:

c#

lambda

linq

I have the following LINQ query:

var q = from bal in data.balanceDetails
        where bal.userName == userName && bal.AccountID == accountNumber
        select new
        {
            date = bal.month + "/" + bal.year,
            commission = bal.commission,
            rebate = bal.rebateBeforeService,
            income = bal.commission - bal.rebateBeforeService
        };

I remember seeing a lambda shorthand for summing the commission field for each row of q. What would be the best way of summing this? Aside from manually looping through the results?

like image 874
Elad Lachmi Avatar asked Jul 21 '26 00:07

Elad Lachmi


1 Answers

It's easy - no need to loop within your code:

var totalCommission = q.Sum(result => result.commission);

Note that if you're going to use the results of q for various different calculations (which seems a reasonable assumption, as if you only wanted the total commission I doubt that you'd be selecting the other bits) you may want to materialize the query once so that it doesn't need to do all the filtering and projecting multiple times. One way of doing this would be to use:

var results = q.ToList();

That will create a List<T> for your anonymous type - you can still use the Sum code above on results here.

like image 76
Jon Skeet Avatar answered Jul 22 '26 15:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!