Hi,
I am trying to build an expression tree Predicate<object> (the object can be any class type) which I want to apply to a PagedCollectionView filter. The issue which I am experiencing though, is pretty strange.
Basically, I want to (in this case) check a string property of a class if it contains a particular substring, but when I set the predicate to to the Filter property of a PagedCollectionView, I get a
"Object reference not set to an instance of an object" exception and I am somewhat stumped. Can anyone help me? Also, please note that this tree can be applied multiple times for the same class (on different properties).
Here is the part of the code i am testing at the moment:
public static Predicate<object> GenerateContainsPredicateEx<C>(Type itemType, string propertyName, List<C> selectedValues, bool isNot)
{
ParameterExpression objParam = System.Linq.Expressions.Expression.Parameter(typeof(object), "x");
UnaryExpression param = System.Linq.Expressions.Expression.TypeAs(objParam, itemType);
System.Linq.Expressions.Expression propertyExp = GetPropertyExpressionForObject(param, propertyName, itemType, typeof(C));
System.Linq.Expressions.Expression condition = null;
if (typeof(C) == typeof(String))
{
List<string> vals = (from s in selectedValues
select Convert.ToString(s))
.ToList();
var propertyStringExp = ExpressionHelper.ToLower(ExpressionHelper.ToString(propertyExp));
var valueExp = System.Linq.Expressions.Expression.Constant(vals[0].ToLower().Trim());
MethodInfo containsMethod = typeof(String).GetMethods()
.Where(m => m.Name == "Contains" && m.GetParameters().Length == 1)
.Single();
condition = System.Linq.Expressions.Expression.Call(propertyExp, containsMethod,
new System.Linq.Expressions.Expression[] { valueExp });
}
if (condition == null)
throw new NotImplementedException();
System.Linq.Expressions.Expression finalCondition = condition;
if (isNot)
finalCondition = System.Linq.Expressions.Expression.Not(finalCondition);
Expression<Func<object, bool>> equalfunction = System.Linq.Expressions.Expression.Lambda<Func<object, bool>>(finalCondition, objParam);
return new Predicate<object>(equalfunction.Compile());
}
The
GetPropertyExpressionForObject method is something I coded to get the correct property for the class if it's a nested property and looks like this (incase this might be causing the problem):
public static System.Linq.Expressions.Expression GetPropertyExpressionForObject(UnaryExpression objParam, string propertyName, Type originalType, Type objType)
{
Type type = originalType;
System.Linq.Expressions.Expression propertyExp = System.Linq.Expressions.Expression.Convert(objParam, originalType);
foreach (string level in propertyName.Split('.'))
{
propertyExp = System.Linq.Expressions.Expression.Property(propertyExp, type, level);
type = type.GetProperty(level).PropertyType;
}
return propertyExp;
}
Thanks in advance!