Return DB results within Date Range

微笑、不失礼 提交于 2019-12-11 23:06:17

问题


In my view, I have an input and select tags for the user to enter a start and end date. When submitted, The controller will search the Model/Database and return entries within the above range.

In my DB, the start and end dates are written as "nvarchars" and in my controller they are taken as strings

Code and Images for reference:

public ActionResult timePeriod(string time)
{
    //Start: month, day, year End: month, day, year --> Numeric values
    string[] times = time.Split(',');                             
    string start = times[0] + " " + times[1] + " " + times[2];
    string end = times[3] + " " + times[4] + " " + times[5];

    //Sample code to test the start date
    viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Contains(start)).ToList();
}

a snippet of the Database values:

Are there any LINQ expression to do this?


回答1:


As the dates are strings, you've nothing better other than using what you have suggested already:

viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Equals(start)).ToList();

I would use Equals as that will be quicker for you. Using Contains is basically like doing a T-SQL LIKE which is much slower.

SELECT *
FROM Table
WHERE StartDate LIKE 'blah'

Using Equals will result in the following equivalent:

SELECT *
FROM Table
WHERE StartDate = 'blah'

Which is much more efficient.



来源:https://stackoverflow.com/questions/27235459/return-db-results-within-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!