[英]Linq query - returning a sum
I am having trouble figuring out how to do something like the following. 我在弄清楚如何执行以下操作时遇到了麻烦。 This is purely pseudocode:
这纯粹是伪代码:
decimal totalActiveCost = (from i in _context.KeyActives
where i.Pk in (active1fk, active2fk, active3fk, active4fk, active5fk, keyActiveFk)
select sum(i.Cost)...`
Then summing the i.Cost. 然后对i.Cost求和。 So basically, I need to return the i.Cost for each "Active" - so, for example, say active1fk is 1, active2fk is 2, and so on.
因此,基本上,我需要为每个“ Active”返回i.Cost-例如,假设active1fk为1,active2fk为2,依此类推。 I need to get the Cost for each of these and sum them up.
我需要获取每一项的成本并将其汇总。
You can have your active foreign keys in a List<T>
like: 您可以将活动外键放在
List<T>
例如:
List<int> activeFks = new List<int> {1,2,3,4,5,};
var sum = (from i in _context.KeyActives
where activeFks.Contains(i.PK)
select i.Cost).Sum();
Or with a method syntax: 或使用方法语法:
var sum = _context.KeyActives
.Where(r=> activeFks.Contains(r.PK))
.Sum(r=> r.Cost);
Something like this will work: 这样的事情会起作用:
List<Int> ids = new List<int>();
ids.Add(1);
ids.Add(2);
var result = _context.KeyActives.
Where(c => ids.Contains(c.id))
.Sum(c => c.Cost);
var ids = new List<int> {active1fk, active2fk, active3fk, active4fk, active5fk, keyActiveFk};
var sum = (from i in _context.KeyActives
where ids.Contains(i.Pk)
select i).Sum(a=> a.Cost);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.