使用可选搜索子句执行 LINQ 查询
我有一个页面,您可以在其中搜索人员。他们可以获取所有人的列表,也可以按某些标准(例如名字或姓氏)对其进行过滤。
到目前为止,我一直在尝试使用这个问题中详细介绍的技术。
因此,我的代码看起来像是
string firstname=...
string lastname=...
var people=from p in People.All()
where (firstname==null || firstname.ToLower()==p.FirstName.ToLower()) &&
(lastname==null || lastname.ToLower()==p.LastName.ToLower())
select p;
在构建查询时遇到空引用错误,但是当名字和姓氏都为空时。删除 where 子句可以消除错误。
为什么这行不通? C# 是否尝试计算 where 子句每个部分的第二部分?应该不是因为短路或者吧?
I have a page where you can search for people. They can either get a list of all people, or filter it by certain criteria such as first or last name.
So far, I have been trying trying to use the technique detailed in this question.
So my code looks like
string firstname=...
string lastname=...
var people=from p in People.All()
where (firstname==null || firstname.ToLower()==p.FirstName.ToLower()) &&
(lastname==null || lastname.ToLower()==p.LastName.ToLower())
select p;
I get a null reference error when building the query however when both firstname and lastname is null. Removing the where clause gets rid of the error.
Why would this not work? Does C# try to evaluate the second part of each part of the where clause? It shouldn't because of the short-circuited OR right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 string.Equals:
这不仅避免了 null 问题,而且还强制您指定字符串比较类型(这是一件好事)。换句话说,您指定在执行不区分大小写的比较时是否使用特定于本地区域性或固定区域性的规则。
Use string.Equals:
Not only does this avoid the null problem, but it forces you to specify a string comparison type (a good thing). In other words, you specify whether to use rules specific to the local or invariant culture when performing the case-insensitive comparison.
您不需要调用
ToLower()
使用 string.compare 代替ignoreCaseyou don't need to call
ToLower()
use string.compare instead with ignoreCase在调用 ToLower 之前确保它不为 null:
Make sure it's not null before calling the ToLower:
当两者都为 null 时它不起作用,因为语句的第一部分将计算为
true
,不允许短路计算。为什么不使用等价规则来翻转语句呢?编辑:我编写了以下内容并在 LINQPad 4 中成功运行它,没有任何问题。我假设对
People.All()
的调用只是返回一个包含完整记录集的IQueryable
?也许可以在此处发布您的异常文本,以便我们可以查看您是否无意中错过了某些内容?It doesn't work when both are null because the first part of the statement will evaluate to
true
, disallowing short-circuiting of the evaluation. Why not use equivalency rules to flip the statement?EDIT: I wrote the following up and ran it successfully in LINQPad 4, with no issues. I'm assuming that the call to
People.All()
simply returns anIQueryable<People>
with the full set of records? Maybe post your exception text here so we can see if there's something you've inadvertently missed?