动态 Linq/Lambda 过滤

发布于 2024-11-07 10:42:08 字数 971 浏览 0 评论 0原文

我有一个返回表达式的方法,用于根据客户需求动态过滤记录,我在做这件事时遇到问题,我想要这样的东西,有

     public Expression<T> FilterCreator<T>(FilterCondition condition, string columnName, object value)
    {

        Expression<Func<Customer, bool>> query;

        // FilterCondition is an enum flag for conditions
        if(condition.Condition == ConditionFlags.EQUALS)
        {
            // here is the problem,
            // i want the emailAddress to be dynamic based on the passed columName parameter of the client 
            // and be able to cast its type of the value that was passed
            query = p => p.EmailAddress == (typeof(p.EmailAddress))value;

           //i want something like this
           // query = p => p.(columnName)=> (typeOf(p.(columnName)))value;

        }
        else if(condition.Condition == ConditionFlags.CONTAINS)
        {
             .....
        } 

        return query;

    }

什么建议吗?提前致谢

I havea method that returns Expression to be used for dynamic filtering of records based on the clients needs, i have a problem in doing it, i want something like this

     public Expression<T> FilterCreator<T>(FilterCondition condition, string columnName, object value)
    {

        Expression<Func<Customer, bool>> query;

        // FilterCondition is an enum flag for conditions
        if(condition.Condition == ConditionFlags.EQUALS)
        {
            // here is the problem,
            // i want the emailAddress to be dynamic based on the passed columName parameter of the client 
            // and be able to cast its type of the value that was passed
            query = p => p.EmailAddress == (typeof(p.EmailAddress))value;

           //i want something like this
           // query = p => p.(columnName)=> (typeOf(p.(columnName)))value;

        }
        else if(condition.Condition == ConditionFlags.CONTAINS)
        {
             .....
        } 

        return query;

    }

any advise guys? thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暖心男生 2024-11-14 10:42:08

您需要构建一个表达式树:

var param = Expression.Parameter<Customer>();
p = Expression.LambdaFunc<Customer, bool>(
    Expression.Call(typeof(object), "Equals", null, //non-generic
                    Expression.Property(param, columnName),
                    Expresssion.Constant(value)
    )
);

You need to build an expression tree:

var param = Expression.Parameter<Customer>();
p = Expression.LambdaFunc<Customer, bool>(
    Expression.Call(typeof(object), "Equals", null, //non-generic
                    Expression.Property(param, columnName),
                    Expresssion.Constant(value)
    )
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文