Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Where with AND OR condition

So I have managed to get this query working

List<string> listStatus = new List<string>() ;  listStatus.add("Text1");  List<string> listMerchants = new List<string>() ; listMerchants.add("Text2");   from item in db.vw_Dropship_OrderItems              where listStatus.Contains(item.StatusCode)                        && listMerchants.Contains(item.MerchantId)              select item; 

Here I would like to check if listStatus and listMerchants are not null only then put them inside WHERE clause.

Like

if listMerchants is null then query will be like

     where listStatus.Contains(item.StatusCode)  

I do not want to use switch or If condition.

Thanks

like image 811
Zeus Avatar asked Nov 12 '09 02:11

Zeus


2 Answers

from item in db.vw_Dropship_OrderItems     where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&     (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)     select item; 

Might give strange behavior if both listMerchants and listStatus are both null.

like image 140
Corey Sunwold Avatar answered Oct 13 '22 11:10

Corey Sunwold


Well, you're going to have to check for null somewhere. You could do something like this:

from item in db.vw_Dropship_OrderItems          where (listStatus == null || listStatus.Contains(item.StatusCode))              && (listMerchants == null || listMerchants.Contains(item.MerchantId))          select item; 
like image 26
Robert Fraser Avatar answered Oct 13 '22 11:10

Robert Fraser