尝试使用表达式树过滤可为空类型

2024-01-09

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

我需要能够过滤任何一个或多个 Person 对象的属性,并且直到运行时我才知道是哪一个。我知道这个问题已经在各地进行了讨论,我已经研究过并且也在使用诸如谓词生成器 http://www.albahari.com/nutshell/predicatebuilder.aspx & 但围绕它们的讨论往往更多地集中在排序和排序上,并且在面对可空类型时,每个人都在为自己的问题而苦苦挣扎。所以我想我会尝试至少构建一个可以解决这些特定场景的补充过滤器。

在下面的示例中,我试图过滤掉在特定日期之后出生的家庭成员。有趣的是,被过滤的对象上的 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 类型版本。因此,在本例中,我们希望将 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 中删除可空性,但会导致以下强制错误。我仍然对此感到困惑,因为我认为“Expression.Convert”方法的目的就是做到这一点。

类型“System.String”和“System.DateTime”之间未定义强制运算符。

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

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

...这导致了一个异常,超出了我对表达式、Lambda 及其相关同类的任何知识...

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

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


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

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

我已经将您的示例调整为更通用(并且有效: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;

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试使用表达式树过滤可为空类型 的相关文章

随机推荐