Home > Net >  How to filter only when date is not null using optional condition
How to filter only when date is not null using optional condition

Time:06-28

I am a little confused about how I can use the date as an optional condition. if there is a date then <= of date, if the date is null then don't filter based on date. My code is like this

DateTime date= DateTime.UtcNow.AddDays(-10);

foreach (var camEvent in dbContext
   .CAM_EVENTS
   .Where(c => c.USER_ID == userID && 
               c.CAM_ID == cam.CAM_ID && 
               c.EVENT_DATE >= date)  //  I want to change this like 
   .OrderByDescending(c => c.DATE)) 
    {...}

I want that line to look something like this

(date && c.EVENT_DATE >= date) 

so it only filter when date is not null, but this is not working.

CodePudding user response:

I'd do the following logic:

(date==null || (c.EVENT_DATE >= date))

CodePudding user response:

You can do something like this:

DateTime date = DateTime.UtcNow.AddDays(-10);

var filteredContext = dbContext
   .CAM_EVENTS
   .Where(c => c.USER_ID == userID && 
               c.CAM_ID == cam.CAM_ID)
   .OrderByDescending(c => c.DATE);

if (date != null) {
  filteredContext = filteredContext.Where(c.EVENT_DATE >= date);
}

foreach (var camEvent in filteredContext) {
  ...
}

CodePudding user response:

You can use a ternary operator, also known as a conditional operator.

foreach (var camEvent in dbContext
   .CAM_EVENTS
   .Where(c => c.USER_ID == userID && 
               c.CAM_ID == cam.CAM_ID && 
               // if date is not null, it will return bool c.EVENT_DATE >= date, otherwise just true
               (date != null ? c.EVENT_DATE >= date : true)) 
 
   .OrderByDescending(c => c.DATE))

  •  Tags:  
  • c#
  • Related