如何使用linq查询生成没有多个if条件的where条件 [英] how to generate where condition without multiple if condition using linq query
问题描述
我有3个搜索文本框值.我需要检查每个变量的string.isnullorEmpty
,并且必须与linq查询进行比较.
I have 3 search textbox values. i need to check string.isnullorEmpty
for each variable and have to compare with the linq query.
我的文字值:
-
制造商
Manufacturer
项目代码
零件号
条件:
-
如果我搜索以上任何一项,我应该得到结果
if i search any one of the above i should get the result
如果我输入3个框值,我应该得到结果
If i enter 3 box values i should get the result
如果我输入2,那么我应该得到结果.
If i enter any 2 then i should get result.
我的代码如下
if (!string.IsNullOrEmpty(manufacturer))
{
var filteredResult = _entity.MaterialMasters.Where(x => x.Manufacturer == manufacturer);
}
if (!string.IsNullOrEmpty(projectcode))
{
var filteredResult = _entity.MaterialMasters.Where(x => x.ProjectCode== projectcode);
}
if (!string.IsNullOrEmpty(part))
{
var filteredResult = _entity.MaterialMasters.Where(x => x.Part== part);
}
为避免多个条件,如何为此使动态where子句出现?请找出解决方案.
To avoid multiple conditions how to make dynamic where clause for this? Please find out the solution for this..
推荐答案
您可以仅标记多个Where
子句
var filteredResult = _entity.MaterialMasters;
if (!string.IsNullOrEmpty(manufacturer))
filteredResult = filteredResult.Where(x => x.Manufacturer == manufacturer);
}
if (!string.IsNullOrEmpty(projectcode))
filteredResult = filteredResult.Where(x => x.ProjectCode == projectcode);
}
if (!string.IsNullOrEmpty(part))
filteredResult = filteredResult.Where(x => x.Part == part);
}
它们将累积工作,这意味着您可以提供1、2或3个参数,并会得到适当的结果.
They will work cumulatively, meaning that you can supply 1, 2 or 3 of the parameters and you'll get the appropriate results.
这篇关于如何使用linq查询生成没有多个if条件的where条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!