LINQ 中的条件总和

  • 本文关键字:条件 LINQ 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 样本中搜索相同的示例,但没有任何线索

更新因此,我在 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

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

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]

你可以这样实现它,以下是根据条件提供的项目计数

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"),
            });

相关内容

  • 没有找到相关文章

最新更新