2015-11-14 74 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(); 
相关问题