0

How can i select multiple columns and calculate the total amount.

For example, in my database i got a few fields which are named:

5hunderedBills, 2hunderedBills, 1hunderedBills, etc.

And the value of those fields are for example:

5, 2, 3

And the sum would be:

5hunderedBills * 5 + 2hunderedBills * 2 + 1hunderedBills * 3

How can i do that with LINQ in one select statement?

2 Answers 2

1

The following code will sum up all three of those columns with weights and return the total sum for all rows.

YourDatabaseContext.Where( item => item.Date == someCriteria).Sum( item => item.FiveHundredBills * 5 + item.TwoHundredBills * 2 + item.OneHundredBills );

If you need a list of a sum for each row, swap methods Sum() and Select():

YourDatabaseContext.Where( item => item.Date == someCriteria).Select( item => item.FiveHundredBills * 5 + item.TwoHundredBills * 2 + item.OneHundredBills );
3
  • Hi, This works but i forgot to mention there should be a where clause to check for date. How can i implement the where clause? Thats all i need to know now. Thank you!
    – Yustme
    May 21, 2010 at 6:53
  • @Yustme, Added Where() clause to LINQ query. For the future, check this Web site for a good set of starting samples: msdn.microsoft.com/en-us/vcsharp/aa336746.aspx and install LinqPad.
    – SethO
    May 21, 2010 at 13:07
  • Hi, I already figured it out via codeproject.com That ms.com site with 101 examples, walked them 50 times already. I'll look into LinqPad. Thanks for your help!
    – Yustme
    May 21, 2010 at 17:04
0
var sum = from b in db.bills
select b.5hunderedBills + b.2hunderedBills + b.1hunderedBills ;

db is the name of your LINQ DataContext and bills is the name of the table in question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.