Linq where clause with multiple conditions and null check

37,824

Solution 1

Won't this work?

QuestionnaireRepo.FindAll(
    q => (q.ExpiredDate == null) || (q.ExpiredDate > DateTime.Now));

Solution 2

If this is Linq-to-Sql or Linq-To-Entities then HasValue will not translate to a SQL Expression and you'll get an exception.

This should do it.

QuestionnaireRepo.FindAll(q => q.ExpiredDate != null && q.ExpiredDate <= DateTime.Now)

Solution 3

There's a couple of ways you could do this, one nice way is using Pipes and Filters, but looking at how you're implementing the above, it doesn't look like you're using this pattern so won't go into it, but its worth googling.

With Pipes and Filters pattern you could do this:

        public static IQueryable<YourType> WithExpiryDate(this IQueryable<YourType> allMyTypes)
        {
            return allMyTypes.Where(f => f.ExpiredDate != null);
        }

        public static IQueryable<YourType> WhereExpiredDateBeforeThanNow(this IQueryable<YourType> allMyTypes)
        {
            return allMyTypes.Where(f => f.ExpiredDate <= DateTime.Now);
        }

And then just go: QuestionnaireRepo.FindAll().WithExpiryDate().WhereExpiredDateBeforeThanNow().SingleOrDefault();

You could also just say:

QuestionnaireRepo.FindAll(q => q.ExpiredDate != null && q.ExpiredDate <= DateTime.Now);

Hope this helps...

Share:
37,824
satyavrat
Author by

satyavrat

Developer working with: Dynamics 365 SharePoint Azure - Cognitive Services | AI | ML Umbraco CMS .NET MVC

Updated on March 18, 2020

Comments

  • satyavrat
    satyavrat about 4 years

    I'm trying to check if a date is null in linq and if it isn't check its a future date.

    QuestionnaireRepo.FindAll(q => !q.ExpiredDate.HasValue || q.ExpiredDate >DateTime.Now).OrderByDescending(order => order.CreatedDate);
    

    I need the second check to only apply if the first is true. I am using a single repository pattern and FindAll accepted a where clause

    ANy ideas? There are lots of similar questions on here but not that give the answer, I'm very new to Linq as you may of guessed :)

    Edit: I get the results I require now but it will be checking the > conditional on null values in some cases. Is this not a bad thing?