开发者

select multiple columns using linq and sum them up

开发者 https://www.devze.com 2022-12-31 17:29 出处:网络
How can i select multiple columns and calculate the total amount. For example, in my database i got a few fields which are named:

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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消