开发者

Linq, how to specify timestamp condition?

I have a logins table whic开发者_JAVA技巧h records all login and logout activities. I want to look at all login activities of a particular user within 24 hrs. how to do it? something like this:

var records = from record in db.Logins
                                where record.Users.UserId == userId
                                    && record.Timestamp <= (DateTime.Now + 24)
                                select record;

record.Timestamp <= (DateTime.Now + 24) is wrong here. I am using C# 3 + L2E.


Apparently the trouble stems from DateTime.Now + 24. This is not possible, because the DateTime type does not specify a + operator for int.

Did you mean: DateTime.Now.AddHours(24)? Or more specifically, -24 (unless your table contains records that will be added in the future).

record.Timestamp >= DateTime.Now.AddHours(-24)

To improve performance, you can store the date in a variable.

DateTime since = DateTime.Now.AddHours(-24);
var records = from record in db.Logins
    where record.Users.UserId == userId
        && record.Timestamp >= since
    select record;

If your timestamp happens to be in ticks, just use since.Ticks instead.


You are attempting to search for all logins between now and 24 hours in the future...

Try:

var records = from record in db.Logins 
              where record.Users.UserId == userId 
                    && record.Timestamp >= (DateTime.Now.AddHours(-24)) 
              select record; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜