c#查询日期之间的数据

c# query data between dates

我想查询 TargetCompletionDate 在开始和结束日期之间的数据,即使我不提供开始和结束日期,它也应该查询数据,下面是我的代码片段,但日期查询似乎不起作用?您注意到任何问题,非常感谢帮助和想法。谢谢

#代码片段

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);

改用endDateForFilter >= x.TargetCompletionDate。由于您希望字段大于开始且小于结束,因此您应该反转条件或操作数,而不是两者。否则你最终会要求一个在结束之后的日期。

条件应如下所示:

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

这看起来确实很奇怪,而且方式很容易在不注意的情况下出错。我第一次输入条件时就错了。

最好重写一下,这样就清楚是怎么回事了。要么使用相同的操作数顺序,要么重写查询,使其看起来像实际要求,例如:

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

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

我更喜欢最后一个选项,因为它看起来像实际的逻辑条件,start <= created && created <= end。这样更容易看出哪里不对

日期条件好像有误,应该是:

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

我已经交换了“<=”条件的字段。