动态 Linq 查询有帮助吗?
如何为以下简单搜索条件编写动态 Linq 查询? 1) 学号 2) 姓氏 3) 姓氏和名字
//if (!String.IsNullOrEmpty(StudentNumber))
var results = (from s in Students
where s.StudentNumber == 1001
select s
);
//else if (!String.IsNullOrEmpty(LastName) & (String.IsNullOrEmpty(FirstName))
var results = (from s in Students
where s.LastName == "Tucker"
select s
);
//else if (!String.IsNullOrEmpty(LastName) & (!String.IsNullOrEmpty(FirstName))
var results = (from s in Students
where s.LastName == "Tucker" && s.FirstName == "Ron"
select s
);
How do you write a dynamic Linq query for the following simple search criteria?
1) StudentNumber
2) LastName
3) LastName and FirstName
//if (!String.IsNullOrEmpty(StudentNumber))
var results = (from s in Students
where s.StudentNumber == 1001
select s
);
//else if (!String.IsNullOrEmpty(LastName) & (String.IsNullOrEmpty(FirstName))
var results = (from s in Students
where s.LastName == "Tucker"
select s
);
//else if (!String.IsNullOrEmpty(LastName) & (!String.IsNullOrEmpty(FirstName))
var results = (from s in Students
where s.LastName == "Tucker" && s.FirstName == "Ron"
select s
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在任何单个查询之外声明您的
results
变量。这将允许您根据不同的条件附加不同的过滤器,并根据需要附加任意数量的过滤器。示例:如果处理 Linq-to-Entities 或 -Sql,请使用
Students.AsQueryable();
键入初始查询,以便过滤发生在数据库而不是应用程序内部。如果您想在查询的第一步之前构建整个
where
,这是相同的逻辑。您正在有条件地构建谓词,因此您将涉及某种 if/else。但是,要首先构建整个谓词,您可以针对 Linq to Objects 的Func
进行构建。您会注意到它是完全相同的 if/else 结构。您可以将其分解为复杂的条件表达式,
但我发现这非常难以理解,当然与更长的 if/else 相比。这个谓词也比我们通过 if/else 构建的谓词更大,因为这个谓词包含所有逻辑,而不仅仅是我们有条件添加的逻辑。
You need to declare your
results
variable outside of any individual query. This will allow you append different filters based upon your varying criteria, and append as many filters as you need. An example:If dealing with Linq-to-Entities or -Sql, type the initial query with
Students.AsQueryable();
so that the filtering happens at the database rather than inside the application.If you want to build the entire
where
before the first step of the query, it's the same logic. You are conditionally building the predicate, so you will have some sort of if/else involved. However, to build the entire predicate first, you could build against aFunc<Student, bool>
for Linq to Objects.You'll notice it's the exact same if/else structure. You could collapse that down into a complicated conditional expression
But I find that pretty well difficult to follow, certainly as compared to the longer if/else. This predicate is also bigger than the one we build via the if/else, because this one contains all the logic, it's not just the logic we conditionally added.