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

标签 c# .net 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 ??

}

示例用法:

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

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

最佳答案

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

我现在无法测试它,但这行不通吗?

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;

}

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

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

}

关于c# - 如何根据用户输入动态构建和返回 linq 谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3932542/

相关文章:

c# - 在 WCF 服务构造函数中发送参数 - 错误

c# - 数据绑定(bind) DataGridView 单元格格式 Int 到月份名称转换

c# - 在 LINQ 查询中按时间顺序对分组查询进行排序

c# - Application_Start 事件中的请求对象

c# - 实例化字体时如何设置多个FontStyles?

c# - WindowClosing方法发生异常时WPF应用程序关闭

c# - IEnumerable 背后的基本原理是什么?

.net - HTML 和编译器

c# - 如何否定 IQueryable 的 Where 子句

sql - Visual Studio 2012 Linq to SQL 可视化工具