如何根据用户输入动态构建和返回linq谓词

对此有点困惑。 基本上我有一个方法,我想返回一个谓词表达式,我可以用作Where条件。 我认为我需要做的就是这样: http : //msdn.microsoft.com/en-us/library/bb882637.aspx但是我有点担心我需要做什么。

方法:

private static Expression<Func> 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); 

我需要这种分离,以便我可以将我的谓词传递到我的存储库并在其他地方使用它。

你有没有检查过PredicateBuilder

谓词只是一个返回布尔值的函数。

我现在无法测试它,但这不会起作用吗?

 private static Expression> 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; } 

编辑:根据马特的评论如果你想组成代表 ,你可以这样做

 private static Expression> GetSearchPredicate(string keyword, int? venueId, string month, int year) { Expression keywordPred = (conf) => true; Expression 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 ...*/); }