Linq 搜索日期
如何使用 Linq 进行搜索时使用日期。我想我在声明中遗漏了一些内容
string searchName = Request.Form["PersonName"];
DateTime searchDateFrom = Request.Form["ReceivedDateFrom"];
DateTime searchDateTo = Request.Form["ReceivedDateTo"];
var Results = (from va in _db.myTable
where ((va.PersonName.Contains(searchName)
&& (va.ApplicationReceivedDate > searchDateFrom
&& va.ApplicationReceivedDate < searchDateTo)
select va).ToList();
how do I used date on searching using Linq. I think I'm missing something on the declaration
string searchName = Request.Form["PersonName"];
DateTime searchDateFrom = Request.Form["ReceivedDateFrom"];
DateTime searchDateTo = Request.Form["ReceivedDateTo"];
var Results = (from va in _db.myTable
where ((va.PersonName.Contains(searchName)
&& (va.ApplicationReceivedDate > searchDateFrom
&& va.ApplicationReceivedDate < searchDateTo)
select va).ToList();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
HttpRequest.Form 是一个 NameValueCollection,可以通过 int/string 获取其中的字符串索引器。也就是说,
Request.Form["ReceivedDateFrom"]
返回一个字符串,您不能在不进行任何转换的情况下将其分配给类型为DateTime
的变量。您可以尝试 DateTime.ParseExact< /a> 方法将字符串转换为DateTime
。但如果您不能保证字符串的格式正确,您可以使用 TryParse 方法。HttpRequest.Form is a NameValueCollection, where you can get strings in it by int/string indexer. That is,
Request.Form["ReceivedDateFrom"]
returns a string, you can't assign it to a variable whose type isDateTime
without any convert. You can try DateTime.ParseExact method to convert the string to aDateTime
. But if you can't guarantee the string has a correct format, you can use a TryParse method.可能是一个拼写错误,但您需要将 searchDateFrom / searchDateTo 转换为 DateTime,并且 linq 语句中有两个额外的开括号
Might be a typo, but you need to cast searchDateFrom / searchDateTo to a DateTime and you have two extra open brackets in your linq statement
我还建议使用更清晰的缩进,这样更容易跟踪和计算括号和其他内容。
I'd also recommand using a cleaner indentation, it's easier to follow and count the brackets and stuff.
这是我设置单元测试来查看发生了什么的时候。
检查括号并从字符串转换为日期时间:
还要检查 & 中的搜索到。
This is when I setup a unit test to see what's going on.
Check your brackets and casting from string to datetime:
Also check the search from & to.