2010-10-14 74 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