Linq查询-返回一个和
本文关键字:一个 查询 返回 Linq | 更新日期: 2023-09-27 17:57:57
我很难弄清楚如何执行以下操作。这纯粹是伪代码:
decimal totalActiveCost = (from i in _context.KeyActives
where i.Pk in (active1fk, active2fk, active3fk, active4fk, active5fk, keyActiveFk)
select sum(i.Cost)...`
然后求和i.Cost。所以基本上,我需要返回每个"活动"的i.Cost——例如,假设active1fk是1,active2fk是2,以此类推。我需要得到每个的Cost并求和。
您可以在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();
或者使用方法语法:
var sum = _context.KeyActives
.Where(r=> activeFks.Contains(r.PK))
.Sum(r=> r.Cost);
这样的东西会起作用:
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);