如何将AND / OR表达式添加到以下动态linq表达式中

时间:2013-01-24 15:43:05

标签: c# .net linq expression-trees dynamic-linq

T是一种可能具有或不具有特定属性的类型,例如“城市”。对于具有名为“City”的属性的类型,我想限制记录,以便只返回Gotham的居民并对其进行排序。

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) 
{

    var type = typeof(T);
    var property = type.GetProperty(ordering);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExp = Expression.Lambda(propertyAccess, parameter);
    MethodCallExpression resultExp = Expression.Call(
                typeof(Queryable), 
                "OrderBy", 
                new     Type[] { type, property.PropertyType }, 
                source.Expression, 
                Expression.Quote(orderByExp));


    string propertyToRestrictOn = "City";
    string restrictedValue = "Gotham";
    var restrictedProperty = type.GetProperty(propertyToRestrictOn);
    if(null ! = restrictedProperty )
    {
      // TODO: What to add here so than only those records are returned that have a 
      // property named City and the value is 'Gotham'???
    }

   return source.Provider.CreateQuery<T>(resultExp);
}

如果可能的话,请在此处命名/链接一些有用的文献,以防我必须创建更复杂的查询,即混合和/或

代码来自 How do I apply OrderBy on an IQueryable using a string column name within a generic extension method?

3 个答案:

答案 0 :(得分:2)

我不太确定我是否理解正确,但我认为几个月前我处于同样的境地。 已发布的代码 here 是我的解决方案。

我认为你应该对第24行特别感兴趣。


编辑:

PropertyInfo p = ... // I used reflection in my examply to get properties with a certain Attribute

var expressionParameter = Expression.Parameter(typeof(SomeClass), "lambda");    
var parameter = new [] { expressionParameter };

var propertyAccess = Expression.Property(expressionParameter, p);
var nullCheck = Expression.NotEqual(propertyAccess, Expression.Constant(null, p.PropertyType));
var nullCheckLambda = Expression.Lambda<Func<SomeClass, Boolean>>(nullCheck, parameter);

var containsMethodInfo = typeof(String).GetMethod("Contains", new[] { typeof(String) });
var contains = Expression.Call(propertyAccess, containsMethodInfo, Expression.Constant("ell"));
var containsLambda = Expression.Lambda<Func<SomeClass, Boolean>>(contains, new[] { expressionParameter });

var predicate = Expression.Lambda<Func<SomeClass, Boolean>>(
// line 24 
Expression.AndAlso(nullCheckLambda.Body, containsLambda.Body), parameter);

Console.WriteLine(predicate.ToString());

答案 1 :(得分:1)

我认为你做得比你更难。在代码的第一部分(OrderBy())中,实际上并不需要生成整个查询表达式,只需要生成整个查询表达式。 在第二部分(可选的Where())中,您可以执行相同的操作,只需添加Expression.Equal()Expression.Constant()

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering)
{
    var type = typeof(T);
    var property = type.GetProperty(ordering);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    // necessary for value types to work
    var cast = Expression.Convert(propertyAccess, typeof(object));
    var orderByExp = Expression.Lambda<Func<T, object>>(cast, parameter);

    IQueryable<T> result = source.OrderBy(orderByExp);

    string propertyToRestrictOn = "City";
    string restrictedValue = "Gotham";
    var restrictedProperty = type.GetProperty(propertyToRestrictOn);
    if (restrictedProperty != null)
    {
        var restrictionParameter = Expression.Parameter(type, "p");
        var restrictionPropertyAccess =
            Expression.MakeMemberAccess(restrictionParameter, restrictedProperty);
        var restrictionEquality =
            Expression.Equal(restrictionPropertyAccess,
                             Expression.Constant(restrictedValue));
        var whereExp =
            Expression.Lambda<Func<T, bool>>(restrictionEquality, restrictionParameter);

        result = result.Where(whereExp);
    }

   return result;
}

此外,如果您的方法不仅仅是订购,我认为您不应该将其称为OrderBy()

答案 2 :(得分:0)

你已经在中途了。你已经有了有序的表达式,所以你只是在Queryable.OrderBy表达式中使用Queryable.Where表达式调用(反之亦然,并不重要)。

if(null != restrictedProperty )
{
    var notEqualExp = Expression.NotEqual(parameter,
                            Expression.Constant(restrictedValue, typeof(string)));
    resultExp = Expression.Call(
            typeof(Queryable), 
            "Where", 
            new Type[] { type }, 
            resultExp, 
            Expression.Lambda(notEqualExp, parameter));
}

暂时没有手工构建表达式,所以这纯粹是从内存中完成的。但是,至少应该让你开始并给你一些工作。

P.S。我会在OrderBy方法调用之前执行此检查。这样您最终会得到Queryably.Where(...).OrderBy(...)。但我想无论如何这都是由提供商翻译的,那么无所谓。但是,我只是做了一些事情来减少生成的查询的任何歧义。