-->

Return DB results within Date Range

2019-09-01 05:51发布

问题:

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.