仅选择时间间隔内的第一条记录

Mar*_*hal 7 c# sql linq linq-to-sql

我有下表

CREATE TABLE [dbo].[DeviceLogs](
    [DeviceLogId] [int] IDENTITY(1,1) NOT NULL,

    [UserId] [nvarchar](50) NULL,
    [LogDate] [datetime2](0) NULL,
)
GO
Run Code Online (Sandbox Code Playgroud)

数据样本

   1     1    2013-05-29 11:05:15   //accepted (its the first occurance for userid 1)
   2     1    2013-05-29 11:05:20   //discarded (within 5 mins from 1st record)
   3     1    2013-05-29 11:07:56   //discarded (within 5 mins from 1st record)
   4     1    2013-05-29 11:11:15   //accepted (after 5 mins from 1st occurance)
   5     2    2013-05-29 11:06:05   //accepted (its the first occurance for userid 2)
   6     2    2013-05-29 11:07:18   //discarded (within 5 mins from 1st record)
   7     2    2013-05-29 11:09:38   //discarded (within 5 mins from 1st record)
   8     2    2013-05-29 11:12:15   //accepted (after 5 mins from 1st occurance)
Run Code Online (Sandbox Code Playgroud)

我想只选择在前一个选定记录5分钟后发生的记录,并包括数据集中的第一个记录

期望的输出是

 1     1     2013-05-29 11:05:15   
 4     1     2013-05-29 11:11:15
 5     2     2013-05-29 11:06:05 
 8     2     2013-05-29 11:12:15
Run Code Online (Sandbox Code Playgroud)

我正在尝试GroupBy,但没有给出日期

db.DeviceLogs.GroupBy(g=>new {g.LogDate.Year, 
                              g.LogDate.Month, 
                              g.LogDate.Day, 
                              g.LogDate.Hour, 
                              g.LogDate.Minutes, 
                              g.UserID})
             .Select(s=>new {UserID=s.Key.UserID, s.???});
Run Code Online (Sandbox Code Playgroud)

先感谢您.

Jan*_* P. 5

var result =
    from log in db.DeviceLogs
    let byId = 
        db.DeviceLogs.Where(item => item.UserId == log.UserId)
    let first =
        byId.First(item => item.LogDate == byId.Min(min => min.LogDate))
    where 
        log.Equals(first) || (log.LogDate - first.LogDate).Minutes > 5
    select log;
Run Code Online (Sandbox Code Playgroud)