我有一个像这样的实体:
public class Product()
{
public string Name { get; set; }
}
我想在 Name
属性上实现关键字搜索,以便对它们进行“或”运算。换句话说,搜索:
勺子刀叉
将在中搜索勺子或刀或叉子 >名称
属性。我为 Product
上的 PredicateBuilder
引入了一种新方法,如下所示:
public static Expression<Func<Product, bool>> ContainsKeywords(params string[] keywords)
{
var predicate = PredicateBuilder.True<Product>();
foreach (var keyword in keywords)
{
var temp = keyword;
predicate = predicate.Or(x => x.Name.Contains(temp));
}
return predicate;
}
并且我在 Web 服务的一个方法中像这样使用它:
var keywords = Request.QueryString["q"].Split(' ');
var products = Repo.GetAll<Product>(); // get all the products from the DB
products = products.Where(Product.ContainsKeywords(keywords));
我的问题我遇到的问题是用户可能选择不进行关键字搜索,在这种情况下 keywords
数组将为空。如果我从 PredicateBuilder.True()
开始,我会得到所有 Products
的列表,无论我输入什么关键字。如果我从 开始PredicateBuilder.False()
,如果用户输入关键字,它会起作用,但如果没有,则返回列表为空,因为所有内容都匹配 false
。
如何修复此问题以获得我想要的行为,即如果未提供关键字,则返回所有 Products
的列表,并返回仅包含 Products
的列表如果提供的话,与关键字相匹配吗?我知道我可以在进行任何处理之前检查关键字数组是否为空,但如果可能的话,我希望 PredicateBuilder 自动处理这种情况。
I have an entity like this:
public class Product()
{
public string Name { get; set; }
}
I want to implement a search for keywords on the Name
property so that they're OR'ed. In other words, a search for:
spoon knife fork
will search for spoon or knife or fork in the Name
property. I introduced a new method for PredicateBuilder
on Product
that looks like this:
public static Expression<Func<Product, bool>> ContainsKeywords(params string[] keywords)
{
var predicate = PredicateBuilder.True<Product>();
foreach (var keyword in keywords)
{
var temp = keyword;
predicate = predicate.Or(x => x.Name.Contains(temp));
}
return predicate;
}
And I'm using it like this in one of my methods for a web service:
var keywords = Request.QueryString["q"].Split(' ');
var products = Repo.GetAll<Product>(); // get all the products from the DB
products = products.Where(Product.ContainsKeywords(keywords));
The problem I'm running into is that the user may choose not to do a keyword search, in which case the keywords
array will be empty. If I start with PredicateBuilder.True<Product>()
, I get a list of all Products
, regardless of what keywords I put in. If I start with PredicateBuilder.False<Product>()
, it works if the user inputs keywords, but if not, then the return list is empty because everything matched false
.
How do I fix this in order to get my desired behavior, which is to return a list of all Products
if no keyword was provided, and return a list of only the Products
that matches the keywords if they were provided? I know I can do a check to see if the keywords array is empty before I do any processing, but if at all possible, I'd like PredicateBuilder
to handle this case automatically.
发布评论
评论(1)