LINQ Where with AND OR condition

Zeus picture Zeus · Nov 12, 2009 · Viewed 154.5k times · Source

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

Answer

Corey Sunwold picture Corey Sunwold · Nov 12, 2009
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.