2016-12-26 115 views
-3

我有這個搜索代碼。在Where子句中使用if/else lambda表達式

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({}); 

} 

現在我需要在最後Where插入此代碼。

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

我應該怎麼做?

+0

你爲什麼要使用3倍「在哪裏」? –

+0

beacuse產品名稱或其他fild可以是空的 – Kianoush

+0

嗯。 「Lambada」 –

回答

5

就個人而言,我不會在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));