Yustme
Yustme

Reputation: 53

select multiple columns using linq and sum them up

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?

Upvotes: 0

Views: 6688

Answers (2)

SethO
SethO

Reputation: 2791

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 );

Upvotes: 1

Jay
Jay

Reputation: 57899

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.

Upvotes: 0

Related Questions