Babak Saeedi
Babak Saeedi

Reputation: 157

Select database entity depending of one of its datetime columns value

I have table article in the database. The table contains Date Expiration column, which can be null.

I want to select article if it's not expired. I've got the following code, but unfortunately, it does not work.

var lstArticle = (from a in Articles.ToList()
                  where a.Block == false
                        && a.DateExpiration < DateTime.Now
                  select a).ToList();

plases help me

Edit:

i use this code, and this working.

var lstArticle = (from a in Articles.ToList()
                  where a.Block == false
                        && ((!a.DateExpiration.HasValue) || (a.DateExpiration.HasValue && a.DateExpiration.Value < DateTime.Now))
                  select a).ToList();

Upvotes: 0

Views: 133

Answers (2)

Oliver
Oliver

Reputation: 9002

If no date means the item has not expired, this should do the trick:

var lstArticle = (from a in Articles.ToList()
                  where a.Block == false
                        && (!a.DateExpiration.HasValue || a.DateExpiration < DateTime.Now)
                  select a).ToList();

If no date means the item has expired, this should work: (Based on your comments you need the first example)

var lstArticle = (from a in Articles.ToList()
                  where a.Block == false
                        && (a.DateExpiration.HasValue && a.DateExpiration < DateTime.Now)
                  select a).ToList();

I have just noticed, you do not need the "new" keyword in your select statement if you are selecting the exact objects from the source.

Upvotes: 5

p.s.w.g
p.s.w.g

Reputation: 149050

Assuming DateExpiration is a DateTime?, use this:

var lstArticle =
    (from a in Articles.ToList()
     where a.Block == false
        && a.DateExpiration.HasValue
        && a.DateExpiration.Value < DateTime.Now
     select new a).ToList();

Upvotes: 1

Related Questions