在Where子句中使用lambda表达式中的if / else

时间:2016-12-26 15:58:22

标签: c# asp.net c#-4.0

我有此搜索代码。

public List<Tbl_Product> ProductSearch(DateTime startdate, DateTime enddate, string productname, int suply)
{
    var q = _db.Tbl_Product
            .Where(model => 
                model.DateReg == startdate && 
                model.DateReg == enddate)
            .Where(model => 
                model.ProductName.Contains(productname))
            .Where({});

}

现在我需要在Last Where中插入此代码。

if(suply == 1)
{
    model.Suply > 0 ;
}
else
{
    model.Suply = 0;
}

我该怎么做?

1 个答案:

答案 0 :(得分:6)

我个人不会在Where子句中这样做,因为这意味着你将suply变量传递给你的数据库。

var q = _db.Tbl_Product
    .Where(model => model.DateReg == startdate 
                 && model.DateReg == enddate
                 && model.ProductName.Contains(productname));

if(suply == 1)
{
    q = q.Where(model => model.Suply > 0);
}
else
{
    q = q.Where(model => model.Suply == 0);
}

但是,如果您真的坚持要一次性完成所有操作:

.Where(model => (suply == 1 && model.Suply > 0)
             || (suply != 1 && model.Suply == 0));