Rank: Newbie
Groups: Registered
Joined: 8/30/2013(UTC) Posts: 3 Location: United States of America
Was thanked: 1 time(s) in 1 post(s)
|
Here is the code for ExpressionBuilder. Code:
public static class ExpressionBuilder
{
public static Expression<Func<TModel, bool>> CreateFilterExpression<TModel>(LambdaExpression parameterExpression, string value)
{
Type propertyType = GetPropertyType(parameterExpression);
Func<Expression, Expression, Expression> operatorExpression = null;
if (propertyType == typeof(string))
{
var containsMethod = typeof(string).GetMethod("Contains");
operatorExpression = (left, target) => Expression.Call(left, containsMethod, target);
}
else if (propertyType == typeof(int) ||
propertyType == typeof(long) ||
propertyType == typeof(short) ||
propertyType == typeof(double) ||
propertyType == typeof(float) ||
propertyType == typeof(bool))
{
operatorExpression = (left, target) => Expression.Equal(left, target);
}
else
{
throw new NotImplementedException("GetType is not imlemented yet for " + propertyType.ToString());
}
return CreateFilterExpression<TModel>(parameterExpression, value, operatorExpression);
}
public static Expression<Func<TModel, bool>> CreateFilterExpression<TModel>(LambdaExpression parameterExpression, string value, Func<Expression, Expression, Expression> createOperator)
{
var expressions = new List<Expression>();
ParameterExpression argParam = parameterExpression.Parameters.First();
var nameMember = GetExpressionMember(parameterExpression);
var prop = (PropertyInfo)nameMember;
object typedValue = Convert.ChangeType(value, prop.PropertyType, null);
Expression equalTarget = Expression.Constant(typedValue, prop.PropertyType);
Expression left = Expression.PropertyOrField(argParam, nameMember.Name);
Expression equals = createOperator(left, equalTarget);
return Expression.Lambda<Func<TModel, bool>>(equals, argParam);
}
public static Expression<Func<TModel, bool>> CombineFilters<TModel>(Expression<Func<TModel, bool>> left, Expression<Func<TModel, bool>> right)
{
var expressionArg = left.Parameters.First();
BinaryExpression andedExpression = Expression.AndAlso(left.Body, Expression.Invoke(right, expressionArg));
return Expression.Lambda<Func<TModel, bool>>(andedExpression, expressionArg);
}
private static Type GetPropertyType(LambdaExpression parameterExpression)
{
var propertyInfo = (PropertyInfo)GetExpressionMember(parameterExpression);
return propertyInfo.PropertyType;
}
public static MemberInfo GetExpressionMember(LambdaExpression lambda)
{
var property = lambda.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
var unary = lambda.Body as UnaryExpression;
if (unary != null)
{
return ((MemberExpression)unary.Operand).Member;
}
throw new NotImplementedException(lambda.Body.GetType().ToString() + " is not implemented");
}
}
And GenericTestModel Code:
public class GenericTestModel<TValue>
{
public TValue Value { get; set; }
}
|