LINQ中的条件求和

时间:2013-01-29 07:06:48

标签: c# linq

这个SQL查询的linq查询是什么

SELECT 
      sum(IIF(jenis = 'primer',1,0)) as sum_primer, 
      sum(IIF(jenis = 'sekunder',1,0)) as sum_sekunder
FROM cooperations

尝试从101 Linq Samples中搜索相同的示例,但没有任何线索

更新 所以,我在C#中使用了这个查询

var query = (from c in db_cooperations.cooperations
              group c by c.jenis into g
              select
              (new
              {
                sum_primer = g.Count(c => c.jenis == "primer"),
                sum_sekunder = g.Count(c => c.jenis == "sekunder")
              })).ToArray();

输出

 sum_primer   sum_sekunder
    0             0 
    0             52
   250            0
    0             0
    0             0

那么,我如何删除零值,然后返回一行

2 个答案:

答案 0 :(得分:5)

var sum_primer = cooperations.Count(c => c.jenis == "primer");
var sum_secunder = cooperations.Count(c => c.jenis == "sekunder");

或者在对数据库的单一查询中

var query = (from c in cooperations
             where c.jenis == "primer" || c.jenis == "sekunder"
             group c by c.jenis
             select new { Jenis = g.Key, Count = g.Count() }
            ).ToDictionary(x => x.Jenis, x => x.Count);

var result = new {
   sum_primer = query.ContainsKey("primer") ? query["primer"] : 0,
   sum_sekunder = query.ContainsKey("sekunder") ? query["sekunder"] : 0
};

将生成此SQL(并且只返回两行):

SELECT COUNT(*) AS [Count], [t0].[jenis] AS [Jenis]
FROM [cooperations] AS [t0]
WHERE ([t0].[jenis] = 'sekunder') OR ([t0].[jenis] = 'primer')
GROUP BY [t0].[jenis]

答案 1 :(得分:5)

你可以像这样实现它,以下是根据条件提供你的物品数量

var data = db.CoOperations.
           GroupBy(x=>x.jenis )
           .select (new {
                sum_primer = g.Count(c => c.jenis == "primer"),
                sum_sekunder = g.Count(c => c.jenis == "sekunder"),
            });