2015-11-14 57 views
1

我試圖寫在我的標準中有大約10個輸入的搜索功能,所有的輸入都是可空的。Linq表達式,其中空字符串作爲通配符

然而,如果輸入爲空,我想它是一個通配符。

例如,如果模型=「」 ID喜歡的搜索查詢到像:

context.products.where(product => product.location == location && product.type == type).tolist(); 

我敢肯定,它可以用if語句但必須有更好的解決方案的負載來完成。 任何想法?

public static List<product> Search(FormCollection formCollection) 
      { 

    var model = formCollection["model"]; 
    var location = formCollection["location"]; 
    var type = formCollection["type"]; 


    var results = context.products.where(product => product.model == model && product.location == location && product.type == type).tolist(); 

    return results; 

    } 

回答

2

事情是這樣的:

var results = context.products 
    .where(product => (model == null || product.model == model) 
       && (location == null || product.location == location) 
       && (type == null || product.type == type)).tolist();