我正在尝试将以下SQL转换为LINQ表达式
SELECT COUNT(ID) AS Count, MyCode
FROM dbo.Archive
WHERE DateSent>=@DateStartMonth AND DateSent<=@DateEndMonth
GROUP BY MyCode
我一直试图关注这个网页作为例子:
Converting SQL containing top, count, group and order to LINQ (2 Entities)
到目前为止,我得到了这个,但我仍然坚持理解新的部分
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()
};
答案 0 :(得分: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 property将包含您分组的属性的值,在本例中为MyCode。
答案 1 :(得分: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相同的输出