[英]Linq passing multiple list in where condition
I am getting result from db by passing filters. 我通过过滤器从数据库中得到结果。 Currently i have passed
code
list and i am getting correct data. 目前,我已通过
code
列表,并且正在获取正确的数据。 Below is the code. 下面是代码。
public DataTable getData(IList<string> Code,
IList<string> category,
IList<string> state,
IList<string> Type,
IList<string> general)
{
DataTable dt = new DataTable();
var result = _db.Sample.Where(x => Code.Contains(x.Code));
if (result == null)
{
return null;
}
else
{
dt = Utility.ToDataTable(result.ToList());
}
return dt;
}
I have to pass 4 more filters ,ie, category, state, type and general
. 我必须再通过4个过滤器,即
category, state, type and general
。 Also i have to check if none of them is null. 我也必须检查它们是否都不为空。
I am not sure how to check the values for null and then pass it to the query. 我不确定如何检查null的值,然后将其传递给查询。
Any suggestions would be appreciated 任何建议,将不胜感激
You can check if all the 5 are null and then execute the lambda
expression. 您可以检查5个值是否全部为空,然后执行
lambda
表达式。 And for adding conditions for 4 extra filters use &&
operator and add it along with code filter. 要为4个额外的过滤器添加条件,请使用
&&
运算符并将其与代码过滤器一起添加。
public DataTable getData(IList<string> Code, IList<string> category, IList<string> state, IList<string> Type, IList<string> general)
{
DataTable dt = new DataTable();
if(code==null)
code=''
if(category==null)
category=''
if(state==null)
state=''
if(general==null)
general=''
var result = _db.Sample.Where(x => (Code.Contains(x.Code) || Code=='') && (category.Contains(x.category)|| category=='') && (state.Contains(x.state)||state=='') && (general.Contains(x.general)||general==''))
if (result == null)
{
return null;
}
else
{
dt = Utility.ToDataTable(result.ToList());
}
return dt;
}
I'm not sure if you want to check contains for all list or just for any one of them. 我不确定是要检查所有列表还是仅检查其中任何一个列表。 I', giving the solution for both
我为双方提供解决方案
public DataTable getData(IList<string> Code, IList<string> category, IList<string> state, IList<string> Type, IList<string> general)
{
DataTable dt = new DataTable();
var result = null;
//result = _db.Sample.Where(x => Code.Contains(x.Code) && category.Contains(x.category) && state.Contains(x.state) && general.Contains(x.general));
//if you wish to check for any one
result = _db.Sample.Where(x => (Code != null && Code.Contains(x.Code)) || (category != null && category.Contains(x.category)) || (state != null && state.Contains(x.state)) || (general != null && general.Contains(x.general)));
if (result == null)
{
return null;
}
else
{
dt = Utility.ToDataTable(result.ToList());
}
return dt;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.