Home > database >  check if a date is null from within a lambda expression and use an alternative date only if it is nu
check if a date is null from within a lambda expression and use an alternative date only if it is nu

Time:09-01

I have some code to search for records created between two input dates (from and to) based upon the createdDate, however we have just imported some old data and not all of the records have a createdDate which means that some records are not returned. My idea is that when there is no createdDate, I use the plannedStartDate instead. This is my original code:

mainTables = mainTables.Where(d => 
   d.n.CreatedDate >= AdminSearchVm.AdminSearch.SubmittedFrom &&
   d.n.CreatedDate <= AdminSearchVm.AdminSearch.SubmittedTo);

but I would like to do something like this:

mainTables = mainTables.Where(d => 
    d.n.CreatedDate == null ? d.n.PlannedStartDate :
    d.n.CreatedDate >= 
           AdminSearchVm.AdminSearch.SubmittedFrom && d.n.CreatedDate == null ? 
           d.n.PlannedStartDate : 
           d.n.CreatedDate <= AdminSearchVm.AdminSearch.SubmittedTo);

CodePudding user response:

try this

mainTables = mainTables.Where(d =>
((d.n.CreatedDate == null && d.n.PlannedStartDate >= AdminSearchVm.AdminSearch.SubmittedFrom)
|| (d.n.CreatedDate != null && d.n.CreatedDate >= AdminSearchVm.AdminSearch.SubmittedFrom))

&& ((d.n.CreatedDate == null && d.n.PlannedStartDate <= AdminSearchVm.AdminSearch.SubmittedIo)
|| (d.n.CreatedDate != null && d.n.CreatedDate <= AdminSearchVm.AdminSearch.SubmittedIo))); 

or you can like this

mainTables = mainTables.Where(d =>
(d.n.CreatedDate == null 
&& d.n.PlannedStartDate >= AdminSearchVm.AdminSearch.SubmittedFrom
&& d.n.PlannedStartDate <= AdminSearchVm.AdminSearch.SubmittedTo)
||                              
(d.n.CreatedDate != null 
&& d.n.CreatedDate >= AdminSearchVm.AdminSearch.SubmittedFrom
&& d.n.CreatedDate <= AdminSearchVm.AdminSearch.SubmittedIo));

CodePudding user response:

Maybe you can use this approach:

mainTables = mainTables
    .Select(t => new { Table = t, Date = (t.n.CreatedDate ?? t.n.PlannedStartDate) })
    .Where(x => x.Date >= AdminSearchVm.AdminSearch.SubmittedFrom && x.Date <= AdminSearchVm.AdminSearch.SubmittedTo)
    .Select(x => x.Table);
  • Related