0

我有 4 个参数,我需要检查 if 条件并给出 where 条件。如何用简单的方式编写它

例子

var param1, param2, param3, param4;

If(param1 !=0 && param2==0 && param3==0 && param4==0)
{
  var query = from x in xx
             where x.y== param1
              select x;
             // where param2,param3, parma4 are 0
}
else If(param1 !=0 && param2 !=0 && param3==0 && param4==0)
{
 var query = from x in xx
             where x.y== param1 && x.z== param2
              select x;
             // where param3, parma4 are 0
}
else if .......

等等

4

1 回答 1

2

您可能正在寻找这样的东西:

var query = from x in xx
            where (param1 == 0 || x.y == param1)
                && (param2 == 0 || x.z == param2)
                && (param3 == 0 || x.a == param3)
                && (param4 == 0 || x.b == param4)
            select x;

这种方法的缺点是您有时会向数据库传递冗余参数。更好的方法是:

var query = xx;
if(param1 != 0)
    query = query.Where(x => x.y == param1);
if(param2 != 0)
    query = query.Where(x => x.z == param2);
if(param3 != 0)
    query = query.Where(x => x.a == param3);
if(param4 != 0)
    query = query.Where(x => x.b == param4);

这需要更多的输入,但会将尽可能小的查询发送到数据库。

于 2012-07-06T05:29:15.343 回答