如何使用linq查询生成没有多个if条件的where条件 [英] how to generate where condition without multiple if condition using linq query

查看:317
本文介绍了如何使用linq查询生成没有多个if条件的where条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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.

我的文字值:

  1. 制造商

  1. Manufacturer

项目代码

零件号

条件:

  1. 如果我搜索以上任何一项,我应该得到结果

  1. 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屋!

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