如何将此 SQL 脚本转换为 LINQ?并保留 Count()?

How can I convert this SQL Script to LINQ? And keep the Count()?

我已经制作并测试了我的 MS SQL 脚本,它运行良好。我一直在慢慢过渡到 LINQ,但在将我的脚本转换为 VB.Net 和 LINQ 时遇到了问题。

SELECT DATEPART(dd,Generated) AS Day, count(ID) as Total
FROM Alarm
WHERE Generated >=CONVERT(VARCHAR(10),DATEADD(MONTH, DATEDIFF(MONTH,0,GETDATE()),0),120)
GROUP BY DATEPART(dd,Generated)

基本上,我要求 table 提供当月每天分组的总行数。为该月的未来几天设置 0 会很棒。任何关于如何将计数转换为 LINQ 的建议都会很棒。

我的代码:

Dim ChartData = (From a In db.Alarms _
Where a.Generated >= FirstDayOfMonth(DateTimeNow) And a.Generated <= LastDayOfMonth(DateTimeNow) _
Group By Day = a.Generated Into Grp = Group, Count() _
Select Grp)

'Get the first day of the month
Public Function FirstDayOfMonth(ByVal sourceDate As DateTime) As DateTime
    Return New DateTime(sourceDate.Year, sourceDate.Month, 1)
End Function

'Get the last day of the month
Public Function LastDayOfMonth(ByVal sourceDate As DateTime) As DateTime
    Dim lastDay As DateTime = New DateTime(sourceDate.Year, sourceDate.Month, 1)
    Return lastDay.AddMonths(1).AddDays(-1)
End Function

成功了,这是代码。

        Dim ChartData = (From a In db.Alarms _
        Where a.Generated >= FirstDayOfMonth(DateTimeNow) And a.Generated <= LastDayOfMonth(DateTimeNow) _
        Group a By CalendarDate = a.Generated.Value.Date Into g = Group _
        Select New With {CalendarDate, .AlarmCount = g.Count()})

你可以这样做。 (我认为 dd 意味着一天...`)

var myDate = new DateTime(); //calculate your date...
Alarms
    .Where(x => x.Generated >= myDate)
    .GroupBy(x => x.Generated.Day)
    .Select (x => new {
        Day = x.Key,
        Total = x.Count()
    }

您可能无法在 sql 中按 x.Generated.Day 进行分组,如果是这样,请在 Where() 之后添加 .AsEnumerable() 以在内存中进行分组。