如何分离 LINQ to SQL 查询中的条件?
我正在使用 ASP.NET 和 C#,我需要使查询条件动态化,
示例:
数据库:
Name Sex
--------------
John Doe M
Jane Doe F
现在我想允许对数据集进行搜索,但如果用户选择按姓名或性别进行搜索,则仅查询将允许对姓名或性别列进行搜索。但是,如果用户选择按姓名和性别进行搜索,则查询将允许按姓名和性别列进行搜索。我的问题是我可以使用 if 语句分离查询以解释搜索的动态性质吗?谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以这样做:
这将根据传入的内容按性别和/或姓名进行过滤。
与
You can do:
This will filter by sex and/or name depending on what is passed in.
is the same as
史蒂文是对的,这是一种又好又简单的方法,并且非常适合您的需求。如果您遇到可能有多个条件语句的情况,那么研究动态 linq 是明智的选择。动态 linq 将允许您编写一个查询,例如:
您可以在此处获取动态 linq 类 http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
祝你好运!
Steven is right, that is one good and easy way to do it and would work great for your needs. If you ever get into a situation where you may have several conditional statements, it would be wise to look into dynamic linq. Dynamic linq would allow you to write a query such as:
You can get the dynamic linq class here http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Good Luck!