将SQL转换为带有计数的linq表达式

4
我正在尝试将以下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() 
      };
2个回答

6
下面的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。

0
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相同的输出


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接