LINQ to Entity 的秒数差异(DiffSeconds 用法)

问题描述 投票:0回答:2

我正在编写一个简单的

LINQ
查询,它将表的行与其自身进行比较。简而言之,表单上有两个数据网格,第一个数据网格显示一些行,每当在第一个网格中选择一行时,第二个数据网格就会填充,条件如下:

找到那些与所选行具有相同代码且接收时间相差小于30秒的行(我的意思是第二个网格中显示的行的接收时间必须早于所选行的接收时间)。

我写了以下代码:

    Call_Log selected = (Call_Log)dataGrid1.SelectedItem;
    var subData = from cLog in callLog
                  where cLog.Check_Create == 1 &&
                  EntityFunctions.DiffSeconds(selected.ReceptionTime,cLog.ReceptionTime) < 30 &&
                  selected.CustomerCode == cLog.CustomerCode &&
                  selected.CalledID == cLog.CalledID &&
                  selected.ID != cLog.ID
                  select cLog;

但它返回一些与所选行相差超过 30 秒的行。我该如何解决这个问题?

评论:

在上面的代码中,我需要那些与所选行相差不到 30 秒的行 (cLog)。

谢谢

c# linq datetime linq-to-entities
2个回答
4
投票

如果

DiffSeconds
返回负值超过 30 秒,您的验证将返回 true。

Math.abs
作为

后尝试比较
Math.Abs(EntityFunctions.DiffSeconds(selected.ReceptionTime,cLog.ReceptionTime)‌​) < 30

0
投票

试试这个。

var subData = from cLog in callLog 
              let diffInTicks = selected.ReceptionTime.Ticks - cLog.ReceptionTime.Ticks
              let thirtySecTicks = new TimeSpan(0, 0, 0, 30, 0).Ticks
              where cLog.Check_Create == 1 && 
                diffInTicks < thirtySecTicks && 
                selected.CustomerCode == cLog.CustomerCode && 
                selected.CalledID == cLog.CalledID && 
                selected.ID != cLog.ID 
              select cLog;
© www.soinside.com 2019 - 2024. All rights reserved.