动态对象的 lambda 表达式

本文关键字:表达式 lambda 对象 动态 | 更新日期: 2023-09-27 18:34:10

我正在尝试为在运行时创建的表构建一个 Lambda 表达式。表达式构建良好,但是当我调用 Compile() 方法时出现此错误"参数类型为"cseval"的表达式。项'不能用于类型为'系统.对象'的委托参数"这是我的职能

    public Func<dynamic, Boolean> GetWhereExp(List<WhereCondition> SearchFieldList, dynamic item)
    {
        ParameterExpression pe = Expression.Parameter(item.GetType(), "c");
        Expression combined = null;
        if (SearchFieldList != null)
        {
            foreach (WhereCondition fieldItem in SearchFieldList)
            {
                //Expression for accessing Fields name property
                Expression columnNameProperty = Expression.Property(pe, fieldItem.ColumName);

                //the name constant to match 
                Expression columnValue = Expression.Constant(fieldItem.Value);
                //the first expression: PatientantLastName = ?
                Expression e1 = Expression.Equal(columnNameProperty, columnValue);
                if (combined == null)
                {
                    combined = e;
                }
                else
                {
                    combined = Expression.And(combined, e);
                }
            }
        }
        var result = Expression.Lambda<Func<dynamic, bool>>(combined, pe);
        return result.Compile();
    }

动态对象的 lambda 表达式

我已经将动态更改为泛型,这段代码对我有用:

    public Func<T, Boolean> GetWhereExp<T>(List<WhereCondition> SearchFieldList, T item)
    {
        var pe = Expression.Parameter(item.GetType(), "c");
        Expression combined = null;
        if (SearchFieldList != null)
        {
            foreach (var fieldItem in SearchFieldList)
            {
                var columnNameProperty = Expression.Property(pe, fieldItem.ColumName);
                var columnValue = Expression.Constant(fieldItem.Value);
                var e1 = Expression.Equal(columnNameProperty, columnValue);
                combined = combined == null ? e1 : Expression.And(combined, e1);
            }
        }
        var result = Expression.Lambda<Func<T, bool>>(combined, pe);
        return result.Compile();
    }

小评论:你的方法返回函数,而不是表达式,所以名称"GetWhereExp"有点不正确。如果你想返回函数,恕我直言,最好使用反射。

UPD:我使用此代码来测试:

            var expressions = new List<WhereCondition>
                {
                    new WhereCondition("Column1", "xxx"),
                    new WhereCondition("Column2", "yyy"),
                };
            var item = new
                {
                    Column1 = "xxx",
                    Column2 = "yyy"
                };
            var func = LinqExpr.GetWhereExp(expressions, (dynamic)item);
            Console.WriteLine(new[] {item}.Count(a => func(a)));