views:

371

answers:

2

Hi,

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?

+1  A: 

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 );
SethO
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
@Yustme, Added Where() clause to LINQ query. For the future, check this Web site for a good set of starting samples: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx and install LinqPad.
SethO
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
A: 
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.

Jay