tags:

views:

47

answers:

2

I have a logins table which 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.

+6  A: 

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.

mafutrct
thank you, I think what I want is something like this: (record.Timestamp.AddHours(24)) <= DateTime.Now
5YrsLaterDBA
@5YrsLaterDBA: That's probably not a good idea. For each record you will have to AddHours before comparing it. With mafutrct's way, you only "add" once and then the rest of the comparisons will be quicker.
Nelson
you are right, I like your 'since' variable
5YrsLaterDBA
A: 

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; 
ck