Gar*_*rom 2 linq lambda expression-trees c#-4.0
我在下面粘贴了我的整个测试应用程序.它相当紧凑,所以我希望这不是问题.您应该能够简单地将其剪切并粘贴到控制台应用程序中并运行它.
我需要能够过滤任何一个或多个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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:2013/02/01
我的想法是将Nullabe类型转换为它的Non-Nullable类型版本.因此,在这种情况下,我们希望将<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);
Run Code Online (Sandbox Code Playgroud)
这实际上是从DateTime中删除Nullable-ness但导致了以下强制错误.我仍然对此感到困惑,因为我认为"Expression.Convert"方法的目的就是这样做.
类型'System.String'和'System.DateTime'之间没有定义强制运算符.
推动我明确地将值解析为DateTime并将其插入混合...
DateTime dt = DateTime.Parse(filterValue);
Expression convertExpression = Expression.Convert(Expression.Constant(dt), propType);
Run Code Online (Sandbox Code Playgroud)
...这导致了一个例外,超过了我对Expressions,Lambdas及其相关人员的任何知识......
"System.DateTime"类型的ParameterExpression不能用于"ConsoleApplication1.Person"类型的委托参数
我不确定还有什么可以尝试的.
问题在于,在生成二进制表达式时,操作数必须是兼容类型.如果没有,您需要在一个(或两个)上执行转换,直到它们兼容.
从技术上讲,你无法将a DateTime与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 },
};
Run Code Online (Sandbox Code Playgroud)
然后使用它:
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;
Run Code Online (Sandbox Code Playgroud)
我不知道这是否适用于所有情况,但它肯定适用于这种特殊情况.
| 归档时间: |
|
| 查看次数: |
6497 次 |
| 最近记录: |