C# 空字符串用作通配符的Linq表达式
我试图编写一个搜索函数,在我的条件中有大约10个输入,所有的输入都可以为空 下面是我的想法,但是如果输入为null,我希望它充当通配符 例如,如果model=”“id希望搜索查询的行为类似:C# 空字符串用作通配符的Linq表达式,c#,asp.net-mvc,linq,C#,Asp.net Mvc,Linq,我试图编写一个搜索函数,在我的条件中有大约10个输入,所有的输入都可以为空 下面是我的想法,但是如果输入为null,我希望它充当通配符 例如,如果model=”“id希望搜索查询的行为类似: context.products.where(product => product.location == location && product.type == type).tolist(); 我相信它可以用大量的if语句来完成,但是必须有更好的解决方案。 有什么想法吗 pub
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;
}
公共静态列表搜索(FormCollection FormCollection)
{
var模型=formCollection[“模型”];
var location=formCollection[“location”];
var type=formCollection[“type”];
var results=context.products.where(product=>product.model==model&&product.location==location&&product.type==type).tolist();
返回结果;
}
类似这样的内容:
var results = context.products
.where(product => (model == null || product.model == model)
&& (location == null || product.location == location)
&& (type == null || product.type == type)).tolist();