集合的表达式树

时间:2014-06-16 16:06:43

标签: c# linq-expressions

我可以手动执行以下操作,但需要使用System.Linq.Expressions进行构建。

.Where(x => x.OrganizationPersonRoles.Any(o => o.OrganizationId == value))

我可以将它构建到.Any并知道我需要为Any方法执行Expression.Call但不知道如何构建内部lambda(o => o.OrganizationId = =值)。

Expression exp = Expression.Parameter(typeof(T), "x");
Type type = typeof(T);
PropertyInfo pi = type.GetProperty("OrganizationPersonRoles");
exp = Expression.Property(exp, pi);
var lambda = Expression.Lambda(exp, arg);

编辑: 它是" .Any"部分我无法弄清楚如何构建表达式。 " OrganizationPersonRoles"是" Person"的集合。类似的东西:

var anyMethod = typeof(Queryable).GetMethods()
    .Where(m => m.Name == "Any")
    .Single(m => m.GetParameters().Length == 2)
    .MakeGenericMethod(typeof(string));

var body = Expression.Call(exp, anyMethod, "Expression For Inner Lambda");
var lambda = Expression.Lambda(body, arg);

1 个答案:

答案 0 :(得分:1)

您可以按如下方式构建lambda o => o.OrganizationId == value

int value = 5;
var xParameter = Expression.Parameter(typeof(T), "x");
var oParameter = Expression.Parameter(typeof(Organization), "o");

var expression =
    Expression.Lambda(
        Expression.Call(
            typeof(Queryable), "Any", new[] { typeof(Organization) },
            Expression.Property(xParameter, "OrganizationPersonRoles"),
            Expression.Constant(
                Expression.Lambda(
                    Expression.Equal(
                        Expression.Property(oParameter, "OrganizationId"),
                        Expression.Constant(value, typeof(int))),
                    oParameter),
                typeof(Expression<Func<Organization, bool>>))),
        xParameter);