尝试使用表达式树过滤Nullable类型

时间:2013-01-31 23:57:58

标签: linq c#-4.0 lambda expression-trees

我已将我的整个测试应用贴在下面。它相当紧凑,所以我希望这不是问题。您应该能够简单地将其剪切并粘贴到控制台应用程序中并运行它。

我需要能够过滤任何一个或多个Person对象的属性,直到运行时我才知道哪个(或多个)。我知道这已经在所有地方进行了讨论,我已经调查过,并且还在使用诸如PredicateBuilder& Dynamic Linq Library但是他们的讨论倾向于更多地关注排序和排序,并且在面对Nullable类型时,每个人都在努力解决自己的问题。所以我认为我会尝试至少构建一个可以解决这些特定场景的补充过滤器。

在下面的示例中,我试图过滤掉在某个特定日期之后出生的家庭成员。关键是被过滤对象上的DateOfBirth字段是DateTime属性。

我得到的最新错误是

  

类型'System.String'和'System.Nullable`1 [System.DateTime]'之间没有定义强制运算符。

问题是什么。我曾尝试过几种不同的铸造和转换方法,但不同程度的失败。最终,这将适用于EF数据库,该数据库也在转换方法(例如DateTime.Parse( - ))上犹豫不决。

非常感谢任何帮助!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> people = new List<Person>();
        people.Add(new Person { FirstName = "Bob", LastName = "Smith", DateOfBirth = DateTime.Parse("1969/01/21"), Weight=207 });
        people.Add(new Person { FirstName = "Lisa", LastName = "Smith", DateOfBirth = DateTime.Parse("1974/05/09") });
        people.Add(new Person { FirstName = "Jane", LastName = "Smith", DateOfBirth = DateTime.Parse("1999/05/09") });
        people.Add(new Person { FirstName = "Lori", LastName = "Jones", DateOfBirth = DateTime.Parse("2002/10/21") });
        people.Add(new Person { FirstName = "Patty", LastName = "Smith", DateOfBirth = DateTime.Parse("2012/03/11") });
        people.Add(new Person { FirstName = "George", LastName = "Smith", DateOfBirth = DateTime.Parse("2013/06/18"), Weight=6 });

            String filterField = "DateOfBirth";
            String filterOper = "<=";
            String filterValue = "2000/01/01";

            var oldFamily = ApplyFilter<Person>(filterField, filterOper, filterValue);

            var query = from p in people.AsQueryable().Where(oldFamily) 
                        select p;

            Console.ReadLine();
        }

        public static Expression<Func<T, bool>> ApplyFilter<T>(String filterField, String filterOper, String filterValue)
        {
            //
            // Get the property that we are attempting to filter on. If it does not exist then throw an exception
            System.Reflection.PropertyInfo prop = typeof(T).GetProperty(filterField);
            if (prop == null)
                throw new MissingMemberException(String.Format("{0} is not a member of {1}", filterField, typeof(T).ToString()));

            Expression convertExpression     = Expression.Convert(Expression.Constant(filterValue), prop.PropertyType);

            ParameterExpression parameter    = Expression.Parameter(prop.PropertyType, filterField);
            ParameterExpression[] parameters = new ParameterExpression[] { parameter };
            BinaryExpression body            = Expression.LessThanOrEqual(parameter, convertExpression);


            Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(body, parameters);


            return predicate;

        }
    }

    public class Person
    {

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        string Nickname { get; set; }
        public int? Weight { get; set; }

        public Person() { }
        public Person(string fName, string lName)
        {
            FirstName = fName;
            LastName = lName;
        }
    }
}

更新:2013/02/01

我的想法是将Nullabe类型转换为它的Non-Nullable类型版本。因此,在这种情况下,我们希望将&lt; Nullable&gt; DateTime转换为简单的DateTime类型。我在调用Expression.Convert调用之前添加了以下代码块来确定并捕获Nullable值的类型。

//
//
Type propType = prop.PropertyType;
//
// If the property is nullable we need to create the expression using a NON-Nullable version of the type.
// We will get this by parsing the type from the FullName of the type 
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
    String typeName = prop.PropertyType.FullName;
    Int32 startIdx  = typeName.IndexOf("[[") + 2;
    Int32 endIdx    = typeName.IndexOf(",", startIdx);
    String type     = typeName.Substring(startIdx, (endIdx-startIdx));
    propType        = Type.GetType(type);
}

Expression convertExpression = Expression.Convert(Expression.Constant(filterValue), propType);

这实际上是从DateTime中删除Nullable-ness但导致了以下强制错误。我仍然对此感到困惑,因为我认为“Expression.Convert”方法的目的就是这样做。

类型'System.String'和'System.DateTime'之间没有定义强制运算符。

继续我明确地将值解析为DateTime并将其插入混合...

DateTime dt = DateTime.Parse(filterValue);
Expression convertExpression = Expression.Convert(Expression.Constant(dt), propType);

...导致一个例外超过了我对Expressions,Lambdas及其相关人员的任何知识......

类型'System.DateTime'的ParameterExpression不能用于'ConsoleApplication1.Person'类型的委托参数

我不确定还有什么可以尝试的。

2 个答案:

答案 0 :(得分:5)

问题在于,在生成二进制表达式时,操作数必须是兼容类型。如果没有,您需要在一个(或两个)上执行转换,直到它们兼容。

从技术上讲,你无法将DateTimeDateTime?进行比较,编译器会隐式地将一个推广到另一个,这允许我们进行比较。由于编译器不是生成表达式的编译器,因此我们需要自己执行转换。

我已经将你的例子调整为更一般(并且工作:D)。

public static Expression<Func<TObject, bool>> ApplyFilter<TObject, TValue>(String filterField, FilterOperation filterOper, TValue filterValue)
{
    var type = typeof(TObject);
    ExpressionType operation;
    if (type.GetProperty(filterField) == null && type.GetField(filterField) == null)
        throw new MissingMemberException(type.Name, filterField);
    if (!operationMap.TryGetValue(filterOper, out operation))
        throw new ArgumentOutOfRangeException("filterOper", filterOper, "Invalid filter operation");

    var parameter = Expression.Parameter(type);

    var fieldAccess = Expression.PropertyOrField(parameter, filterField);
    var value = Expression.Constant(filterValue, filterValue.GetType());

    // let's perform the conversion only if we really need it
    var converted = value.Type != fieldAccess.Type
        ? (Expression)Expression.Convert(value, fieldAccess.Type)
        : (Expression)value;

    var body = Expression.MakeBinary(operation, fieldAccess, converted);

    var expr = Expression.Lambda<Func<TObject, bool>>(body, parameter);
    return expr;
}

// to restrict the allowable range of operations
public enum FilterOperation
{
    Equal,
    NotEqual,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
}

// we could have used reflection here instead since they have the same names
static Dictionary<FilterOperation, ExpressionType> operationMap = new Dictionary<FilterOperation, ExpressionType>
{
    { FilterOperation.Equal,                ExpressionType.Equal },
    { FilterOperation.NotEqual,             ExpressionType.NotEqual },
    { FilterOperation.LessThan,             ExpressionType.LessThan },
    { FilterOperation.LessThanOrEqual,      ExpressionType.LessThanOrEqual },
    { FilterOperation.GreaterThan,          ExpressionType.GreaterThan },
    { FilterOperation.GreaterThanOrEqual,   ExpressionType.GreaterThanOrEqual },
};

然后使用它:

var filterField = "DateOfBirth";
var filterOper = FilterOperation.LessThanOrEqual;
var filterValue = DateTime.Parse("2000/01/01"); // note this is an actual DateTime object

var oldFamily = ApplyFilter<Person>(filterField, filterOper, filterValue);

var query = from p in people.AsQueryable().Where(oldFamily) 
            select p;

我不知道这是否适用于所有情况,但它肯定适用于这种特殊情况。

答案 1 :(得分:1)

如果您询问body变量,则可以看到您创建的表达式的正文基本上是DateOfBirth <= '2000/01/01'

虽然在脸上看起来似乎是正确的,但是你试图将该主体分配给一个带Person的函数(这是你的例子中T)并返回一个bool。您需要更改逻辑,以便主体将输入反映为Person对象,访问DateOfBirth的该实例上的Person属性,然后执行比较。

换句话说,你的表达式的主体必须取T,在其上找到正确的属性,然后进行比较。