LINQ中的条件多字段搜索和过滤 [英] Conditional Multiple Fields Searching and Filtering in LINQ

查看:75
本文介绍了LINQ中的条件多字段搜索和过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有下表:

Person:
  PersonID,
  Name,
  Age,
  Gender

并且我们提供了搜索功能,允许用户根据名称和/或年龄搜索表格.

And we are providing a search function that allows users to search the table according to the name and/or the age.

编写SQL(或LINQ)查询的棘手部分是用户可以选择同时搜索两个字段,也可以搜索任何一个字段,也可以不搜索任何字段.如果他想搜索所有内容,则只需将文本框留空.

The tricky part in writing the SQL ( or LINQ) query is that the users can choose to search for both field, or any one field, or no field. If he wants to search for all then he would just have to leave the textbox blank.

做到这一点的逻辑可以写成如下:

The logic to do this can be written as follows:

var p;
if(Name_TextBox=='')
{
   p=from row in person
        select row ;
}
else 
{
  p= from row in person
      where row.Name=Name_TextBox
        select row ;
}
// repeat the same for age

现在过了一段时间,代码变得非常冗长和混乱……我该如何使用 if-else 将其压缩成一个查询?

Now after a while the code gets very long and messy... How can I compress the above into a single query with no if-else?

推荐答案

我在SQL中使用的一种备选方案也可以在Linq中实现

One alternative which I have used in SQL which could be implemented in Linq too is

var p = from p in Person
       where p.Name == Name_TextBox || Name_TextBox == String.Empty
       select p;

(请注意,您的"linq"使用的是SQL语法,该语法不会编译.同样,如果不直接分配值就不能像声明的那样声明var)

(Note that your 'linq' is using SQL syntax, which won't compile. Also you can't declare a var as you are doing without directly assigning a value)

这篇关于LINQ中的条件多字段搜索和过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆