List <object> .Contains Expression Tree </object>

时间:2009-05-04 16:51:13

标签: c# linq lambda

我想建立一个等同于预期的表达式......

Expression<Func<ReferencedEntity, bool>> expected = (ReferencedEntity referencedEntity) => foreignKeys.Contains(referencedEntity.Id);
Expression<Func<ReferencedEntity, bool>> actual;

foreignKeys类型是List<object>

这是我到目前为止所做的,我认为它会使用Expression.Call()方法但不确定如何去做。

ParameterExpression entityParameter = Expression.Parameter(typeof(TReferencedEntity), "referencedEntity");
MemberExpression memberExpression = Expression.Property(entityParameter, "Id");
Expression convertExpression = Expression.Convert(memberExpression, typeof(object)); //This is becuase the memberExpression for Id returns a int.

//Expression containsExpression = Expression.Call(????

//actual = Expression.Lambda<Func<TReferencedEntity, bool>>(????, entityParameter);

谢谢你的帮助。

2 个答案:

答案 0 :(得分:11)

如果没有塞缪尔的建议,这是我无法做到的解决方案......

    /// <summary>
    /// 
    /// </summary>
    /// <param name="foreignKeys"></param>
    /// <returns></returns>
    private Expression<Func<TReferencedEntity, bool>> BuildForeignKeysContainsPredicate(List<object> foreignKeys, string primaryKey)
    {
        Expression<Func<TReferencedEntity, bool>> result = default(Expression<Func<TReferencedEntity, bool>>);

        try
        {
            ParameterExpression entityParameter = Expression.Parameter(typeof(TReferencedEntity), "referencedEntity");
            ConstantExpression foreignKeysParameter = Expression.Constant(foreignKeys, typeof(List<object>));
            MemberExpression memberExpression = Expression.Property(entityParameter, primaryKey);
            Expression convertExpression = Expression.Convert(memberExpression, typeof(object));
            MethodCallExpression containsExpression = Expression.Call(foreignKeysParameter
                , "Contains", new Type[] { }, convertExpression);

            result = Expression.Lambda<Func<TReferencedEntity, bool>>(containsExpression, entityParameter);

        }
        catch (Exception ex)
        {
            throw ex;
        }

        return result;
    }

答案 1 :(得分:8)

我不知道解决方案,但我知道你怎么能得到它。创建一个虚拟函数,它接收Expression<Func<ReferencedEntity, bool>>并将它传递给你的lambda。使用调试器,您可以检查编译器如何为您创建表达式。