linq相当于按日期和小时计算记录

时间:2016-05-26 20:32:12

标签: c# linq

我有一个SQL查询,但在c#LINQ中它的等价物是什么?

SELECT CAST(DateAdded as date) AS ForDate,
       DATEPART(hour,DateAdded) AS OnHour,
       COUNT(*) AS Totals
FROM [TABLE1].[dbo].[PartValues]

GROUP BY CAST(DateAdded as date),
       DATEPART(hour,DateAdded)
       Order by ForDate Desc,
       OnHour Desc

这个想法是按日期和小时计算记录 - 如下:

ForDate OnHour  Totals
2016-05-25  9   36
2016-05-25  8   60
2016-05-25  7   70
2016-05-25  6   12
2016-05-24  21  24
2016-05-24  20  72
2016-05-24  19  24
2016-05-24  14  120

2 个答案:

答案 0 :(得分:0)

您可以使用DbFunctions.TruncateTime提取DateAdded列的日期部分。这段代码应该有效:

var result = context.PartValues
    .GroupBy(x => new
    {
        Date = DbFunctions.TruncateTime(x.DateAdded), //Extract Date only (time part is 0)
        Hour = x.DateAdded.Hour
    }).Select(g => new
    {
        g.Key.Date,
        g.Key.Hour,
        Total = g.Count()
    })
    .ToList();

答案 1 :(得分:0)

请参阅以下代码:

var results = context.partValues.GroupBy(r =>
   new DateTime(r.dateAdded.Year,
                r.dateAdded.Month,
                r.dateAdded.Day,
                r.dateAdded.Hour, 0, 0),
   (d, r) => new { date = d, totals = r.Count() });