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

Phi*_*lip 4 c# linq linq-to-sql

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

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

我一直在尝试关注此网页作为示例:
将包含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() });
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助


更新:
你能解释一下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() 
      };
Run Code Online (Sandbox Code Playgroud)

Zyp*_*rax 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() 
          };
Run Code Online (Sandbox Code Playgroud)

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