在我看来,我有一个输入和选择标签,供用户输入开始和结束日期。 提交时,控制器将搜索模型/数据库并返回上述范围内的条目。
在我的数据库中,开始和结束日期写为nvarchars,在我的控制器中,它们被作为字符串
代码和图片供参考:
public ActionResult timePeriod(string time) { //开始:月,日,年结束:月,日,年 - >数值 string [] times = time.Split(','); string start = times [0] ++ times [1] ++ times [2]; string end = times [3] ++ times [4] ++ times [5]; //测试开始日期的示例代码 viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Contains(start))ToList(); }数据库值的一个片段:
是否有任何LINQ表达式来执行此操作?
解决方案由于日期是字符串,除了使用你已经建议:
viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Equals(start ))ToList();我将使用等于更快你使用包含基本上就像做一个T-SQL LIKE 这慢得多。
SELECT * FROM Table WHERE StartDate LIKE'blah'使用等于将导致以下等价物:
SELECT * FROM Table WHERE StartDate ='blah'哪种效率更高。 / p>
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?
解决方案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.
更多推荐
在数据范围内返回数据库结果
发布评论