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

Mat*_*rts 8 .net c# linq

对此有点困惑.基本上我有一个方法,我想返回一个谓词表达式,我可以用作Where条件.我认为我需要做的是类似于:http://msdn.microsoft.com/en-us/library/bb882637.aspx但我对我需要做的事情有点困惑.

方法:

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 ??

}
Run Code Online (Sandbox Code Playgroud)

用法示例:

var predicate = GetSearchPreducate(a,b,c,d);
var x = Conferences.All().Where(predicate);
Run Code Online (Sandbox Code Playgroud)

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

tsi*_*lar 12

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

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

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;

}
Run Code Online (Sandbox Code Playgroud)

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

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 ...*/);

}
Run Code Online (Sandbox Code Playgroud)


Mat*_*ott 10

你有没有检查过PredicateBuilder