Linq查询 - 返回一个总和

时间:2014-04-10 17:36:45

标签: c# sql linq

我无法弄清楚如何执行以下操作。这纯粹是伪代码:

decimal totalActiveCost = (from i in _context.KeyActives 
                           where i.Pk in (active1fk, active2fk, active3fk, active4fk, active5fk, keyActiveFk) 
                           select sum(i.Cost)...`

然后总结i.Cost。基本上,我需要为每个" Active"返回i.Cost。 - 例如,假设active1fk为1,active2fk为2,依此类推。我需要为这些中的每一个获得成本并总结它们。

3 个答案:

答案 0 :(得分:5)

您可以将活动外键放在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);

答案 1 :(得分:1)

这样的事情会起作用:

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

答案 2 :(得分:1)

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