我有一個這樣的實體:LINQ PredicateBuilder多個或與PredicateBuilder.True啓動<>
public class Product()
{
public string Name { get; set; }
}
我想要實現有關Name
屬性關鍵字的搜索,這樣他們或運算。換句話說,對於一個搜索:
勺刀叉
將搜索勺子或刀或叉在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));
我的問題m遇到的問題是用戶可能選擇不執行關鍵字搜索,在這種情況下,keywords
數組將爲空。如果我開始PredicateBuilder.True<Product>()
,我得到的所有Products
的列表,無論什麼關鍵詞,我把。如果我開始PredicateBuilder.False<Product>()
,它的工作原理如果用戶輸入的關鍵詞,但如果沒有,則返回列表是空的,因爲一切都匹配false
。
如何解決這個問題,以獲得我的期望的行爲,這是返回如果未提供關鍵字的所有Products
的列表,並返回的僅是關鍵字匹配Products
名單,如果他們提供的?我知道我可以做一次檢查,看看是否關鍵字數組爲空,我做任何處理之前,但如果可能的話,我想PredicateBuilder
自動處理這種情況。
是的,這是最好的,但他特別要求一種方式,而不檢查列表是否爲空。 – Jacob 2011-02-02 02:42:09