繁体   English   中英

使用count将SQL转换为linq表达式

[英]Convert SQL to linq expression with count

我试图将以下SQL转换为LINQ表达式

SELECT    COUNT(ID) AS Count, MyCode
FROM      dbo.Archive
WHERE     DateSent>=@DateStartMonth AND DateSent<=@DateEndMonth
GROUP BY  MyCode

我一直试图关注这个网页作为例子:
将包含top,count,group和order的SQL转换为LINQ(2个实体)

到目前为止,我得到了这个,但我仍然坚持理解新的部分

var res = (from p in db.Archives
           where (p.DateSent>= dateStartMonth) && (p.DateSent< dateToday)
           group p by p.MyCode into g
           select new { ??????MyCode = g.something?, MonthlyCount= g.Count() });

在此先感谢您的帮助


更新:
你能解释一下g.Key是什么吗? 我不明白那个变量来自哪里或它是指什么? 我的意思是如果我分组4个不同的东西? 我如何参考每一个?

var res = from archive in db.Archives
      where archive.DateSent >= dateStartMonth &&
            archive.DateSent < dateToday
      group archive by archive.MyCode, archive.Extra into archiveGrp
      select new 
      { 
           MyCode = archiveGrp.Key, 
           Extra = archiveGrp.???
           MonthlyCount = archiveGrp.Count() 
      };

下面的LINQ语句应该有效:

var res = from archive in db.Archives
          where archive.DateSent >= dateStartMonth &&
                archive.DateSent < dateToday
          group archive by archive.MyCode into archiveGrp
          select new 
          { 
               MyCode = archiveGrp.Key, 
               MonthlyCount = archiveGrp.Count() 
          };

请注意, Key属性将包含您分组的属性的值,在本例中为MyCode。

from p in archive
where p.DateSent >= dateStartMonth && p.DateSent < dateToday
group p by p.MyCode into g
select new { Count = g.Count(), MyCode = g.Key  }

产生与Linqpad中的Sql相同的输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM