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

时间:2015-01-15 20:44:53

标签: sql asp.net sql-server vb.net linq

我制作并测试了一个完美运行的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)

基本上,我要求表格给出每天分组的月份的总行数。将它放在本月的未来几天是很棒的。关于如何将计数转换为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()})

1 个答案:

答案 0 :(得分:-1)

你可以这样做。 (我认为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分组,如果是,请在.AsEnumerable()之后添加Where()以在内存中进行分组。