【问题标题】:Linq to Get Values within date Not bringing correct valueLinq 在日期内获取值没有带来正确的值
【发布时间】:2021-01-30 12:06:58
【问题描述】:

我有这个 Linq 查询,我想用它来列出具有日期范围的项目。

代码如下:

[HttpPost]
    public JsonResult AjaxMethod(string search, DateTime startDate, DateTime endDate)
    {
        var stDate = startDate.Date;
        var enDate = endDate.Date;
        var str = search;
       
        List<LoanAccount> loanAccounts  = (from loanCustomer in db.LoanAccounts
                                           where (loanCustomer.Account_Number.Contains(search) || search == null) 
                                           && (loanCustomer.Date_Opened >= stDate && loanCustomer.Date_Opened <= enDate)
                                           select loanCustomer).ToList();
        return Json(loanAccounts);
    }

如果 stdate 是 23/01/2021 并且 endate 是 23/01/2021,它不会返回当天的值。如果我将结束日期更改为 24/01/2021,它将带来 23/01/2021 的数据,并且不包括 24/01/2021。是不是我遗漏了什么?

【问题讨论】:

    标签: c# linq asp.net-ajax


    【解决方案1】:

    23-01-202123-01-2021 00:00:00 相同。因此比较 23-01-2021 14:00:00 &lt;= 23-01-2021 将因此是 false

    换句话说,日期范围23-01-202123-01-2021 不是一个范围,因为开始 (23-01-2021 00:00:00) 和结束 (23-01-2021 00:00:00) 是相同的。

    相反,您需要将结束日期推迟一天,然后只取严格小于结束日期的所有内容。所以范围是23-01-202124-01-2021,本质上是23-01-2021 00:00:0024-01-2021 00:00:00

    因此,您的解决方案应该是:

    var stDate = startDate.Date;
    var enDate = endDate.Date.AddDays(1);
    var str = search;
    
    List<LoanAccount> loanAccounts  =
        (from loanCustomer in db.LoanAccounts
        where (loanCustomer.Account_Number.Contains(search) || search == null)
        //                          Notice the "strictly less" comparison  v
        && (loanCustomer.Date_Opened >= stDate && loanCustomer.Date_Opened < enDate)
        select loanCustomer).ToList();
    

    【讨论】:

    • 我使用的
    • @uthumvc 在我的示例中设置enDate = endDate.Date.AddDays(1) 之后也是?
    • 哦。我错过了,让我试试
    • 现在工作正常。但是为什么我们必须放那个 .AddDays(1)。
    • @uthumvc 我在答案中添加了一些细节,希望它更清楚
    【解决方案2】:

    DateDiffDay 函数计算 startDate 和 endDate 之间的天数。 所以你可以试试这个:

    
     where (loanCustomer.Account_Number.Contains(search) || search == null)
           && EF.Functions.DateDiffDay(stDate, loanCustomer.Date_Opened)>=0 
           && EF.Functions.DateDiffDay(loanCustomer.Date_Opened, enDate) >=0
    
    

    【讨论】:

    • 这是否意味着我不必使用 var enDate = endDate.Date.AddDays(1);
    • 是的,这意味着您根本不应该使用 AddDays。还有 DateDiffHour 或 DateDiffMinute 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多