2010-10-14 70 views
8

有點困難。基本上我有一個方法,我想返回一個謂詞表達式,我可以用作Where條件。 我認爲我需要做的是類似於此:http://msdn.microsoft.com/en-us/library/bb882637.aspx但我有點卡住,我需要做什麼。如何根據用戶輸入動態構建並返回一個linq謂詞

方法:

private static Expression<Func<Conference, bool>> GetSearchPredicate(string keyword, int? venueId, string month, int year) 
{ 
    if (!String.IsNullOrEmpty(keyword)) 
    { 
     // Want the equivilent of .Where(x => (x.Title.Contains(keyword) || x.Description.Contains(keyword))); 
    } 
    if (venueId.HasValue) 
    { 
     // Some other predicate added... 
    } 

    return ?? 

} 

實例應用:

var predicate = GetSearchPreducate(a,b,c,d); 
var x = Conferences.All().Where(predicate); 

我需要這種分離,這樣我可以通過我的謂語進入我的倉庫,並在其他地方使用它。

回答

8

您檢查了PredicateBuilder

+1

不錯,正是我想要的:) – 2010-10-14 12:24:33

10

謂詞只是一個返回布爾值的函數。

我現在無法測試它,但是不會工作嗎?

private static Expression<Func<Conference, bool>> GetSearchPredicate(string keyword, int? venueId, string month, int year) 
{ 
    if (!String.IsNullOrEmpty(keyword)) 
    { 
     //return a filtering fonction 
     return (conf)=> conf.Title.Contains(keyword) || Description.Contains(keyword))); 
    } 
    if (venueId.HasValue) 
    { 
     // Some other predicate added... 
     return (conf)=> /*something boolean here */; 
    } 

    //no matching predicate, just return a predicate that is always true, to list everything 
    return (conf) => true; 

} 

編輯:根據Matt的評論 如果你想組成代表,你可以繼續這樣

private static Expression<Func<Conference, bool>> GetSearchPredicate(string keyword, int? venueId, string month, int year) 
{ 
    Expression<Func<Conference, bool> keywordPred = (conf) => true; 
    Expression<Func<Conference, bool> venuePred = (conf) => true; 
    //and so on ... 


    if (!String.IsNullOrEmpty(keyword)) 
    { 
     //edit the filtering fonction 
     keywordPred = (conf)=> conf.Title.Contains(keyword) || Description.Contains(keyword))); 
    } 
    if (venueId.HasValue) 
    { 
     // Some other predicate added... 
     venuePred = (conf)=> /*something boolean here */; 
    } 

    //return a new predicate based on a combination of those predicates 
    //I group it all with AND, but another method could use OR 
    return (conf) => (keywordPred(conf) && venuePred(conf) /* and do on ...*/); 

} 
+1

呀,只是喜歡這個。只需從中抽取(x => something)部分並將其保存到Expression >中。 – Euphoric 2010-10-14 11:23:36

+0

乾杯,但我想建立在過濾器/謂詞之上。因此,如果傳入關鍵字,請爲其添加過濾條件。如果一個venueId也通過了,那麼添加這個過濾器......這就是所有讓我困惑的地方...... – 2010-10-14 11:39:19

+0

當你在需要謂詞的地方使用表達式時,使用exp.Compile() – Les 2010-10-14 11:40:15