Home > database >  c# query data between dates
c# query data between dates

Time:02-03

I wanted to query data where TargetCompletionDate is between start and end date , it should also query data even I don't provide start and end date , below is my code snippet but the date query does not seem to work ? Any issue you have notice , would really appreciate help and ideas. Thanks.

#code snippert

public async Task<IPagedList<TransactionListDto>> GetMyTransactionListAsync(DateTime? startDate = null , 
                      DateTime? endDate = null)
        {
        
            DateTime startDateForFilter = startDate ?? DateTime.MinValue;
            DateTime endDateForFilter = endDate ?? DateTime.MinValue;


            var filteredData = mappedData
                 .Where(x => x.TargetCompletionDate >= startDateForFilter 
                           && endDateForFilter <= x.TargetCompletionDate);
            var paginatedData = await AppUtil.MultipleSort<TransactionListDto>(
                        filteredData.AsQueryable(), 
                        sortKeys,
                        sortOrders)
              .ToPagedListAsync(page, pageSize);

CodePudding user response:

Use endDateForFilter >= x.TargetCompletionDate instead. Since you want the field to be greater than the start and less than the end, you should reverse the condition or the operands, not both. Otherwise you end up asking for a date that's after the end.

The condition should look like this:

x.TargetCompletionDate >= startDateForFilter && 
      endDateForFilter >= x.TargetCompletionDate

This really looks weird and is way to easy to get wrong without noticing. I got this wrong the first time I typed the condition.

It's better to rewrite it so it's clear what's going on. Either use the same operand order, or rewrite the query so it reads like the actual requirement, eg:

x.TargetCompletionDate >= startDateForFilter && 
x.TargetCompletionDate <= endDateForFilter 

or

startDateForFilter <= x.TargetCompletionDate  && 
x.TargetCompletionDate <= endDateForFilter 

I prefer the last option, because it looks like the actual logical condition, start <= created && created <= end. It's easier to see that something's wrong this way

CodePudding user response:

The date condition seems to be incorrect, it should be:

var filteredData = mappedData
                 .Where(x => x.TargetCompletionDate >= startDateForFilter 
                           &&  x.TargetCompletionDate <= endDateForFilter);

I have swapped the fields of the '<=' condition.

  •  Tags:  
  • Related