I'm new to expression Tree and I need to convert the below lambda to Expression Tree
Data.Where(s => s.Property.ToString().StartsWith("My Search Data"));
However I have done upto
Data.Where(s => s.Property.StartsWith("My Search Data");
Now I Need to use the ToString Method before Using StartsWith.
Below is my sample code.
ParameterExpression e = Expression.Parameter(typeof(T), "e");
PropertyInfo propertyInfo = typeof(T).GetProperty(field);
MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
ConstantExpression c = Expression.Constant(data, typeof(string));
MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
Expression call = Expression.Call(m, mi, c);
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(call, e);
query = query.Where(lambda);
Consider using the overloads that allow you to access members by name instead. It will make this significantly easier to do.
// Data.Where(s => s.Property.ToString().StartsWith("My Search Data"));
var property = "Property";
var filter = "My Search Data";
var param = Expression.Parameter(typeof(T));
var body = Expression.Call(
Expression.Call(
Expression.Property(param, property),
"ToString",
null
),
"StartsWith",
null,
Expression.Constant(filter)
);
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
The ideea is that you have to get "ToString" method from System.Object. Because it is a virtual method, the Runtime can dispatch the call on your real object.
Note: IData is your whatever data that has a property named "Property".
ParameterExpression e = Expression.Parameter(typeof(IData), "e");
PropertyInfo propertyInfo = typeof(IData).GetProperty("Property");
MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
var toString = typeof (Object).GetMethod("ToString");
ConstantExpression c = Expression.Constant(data, typeof(string));
MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
var toStringValue = Expression.Call(m, toString);
Expression call = Expression.Call(toStringValue, mi, c);
Expression<Func<IData, bool>> lambda = Expression.Lambda<Func<IData, bool>>(call, e);
Related
i want to achieve this simple lambda with expressions.
x => x.myDictionary["key"] == "value"
This is I have done so far.
var parameterExpression = Expression.Parameter(typeof(T), "p");
var memberExpression = Expression.Property(parameterExpression, "myDictionary");
var expressionCall = Expression.Call(memberExpression, typeof(IDictionary<string, string>).GetMethod("get_Item"), Expression.Constant("key"));
var eq1 = Expression.Equal(expressionCall, Expression.Constant("value"));
var lambda = Expression.Lambda(eq1, parameterExpression);
q.Where(lambda);
But the filter is not working. Do you have any ideas?
I'v build a method to construct expression dynamically, below is my code:
public static Expression<Func<T, bool>> BuildStringEqualLambda(string propertyName, string propertyValue)
{
ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");
Expression propertyExp = Expression.Property(parameterExp, propertyName);
Expression right = Expression.Constant(propertyValue);
Expression e1 = Expression.Equal(propertyExp, right);
return Expression.Lambda<Func<T, bool>>(e1, new ParameterExpression[] { parameterExp });
}
But if the lambda like
c=>c.user.code == 'XXX'
and I invoke method like below:
BuildStringEqualLambda("user.code","XXX");
The method report error.
So my question is how to get build expression (c=>c.user.code == 'XXX') dynamically
Instead of:
ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");
Expression propertyExp = Expression.Property(parameterExp, propertyName);
You need to go deeper for each property:
ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");
Expression propertyExp = parameterExp;
foreach (var property in propertyName.Split('.')) {
propertyExp = Expression.PropertyOrField(propertyExp, property);
}
I'm trying to implement expression tree with linq.I am getting error state as cannot convert lambdaexpression to expression. Please help i checked other solution but couldn't help as much ! Below is my code
ParameterExpression pe = Expression.Parameter(typeof(Person), "p");
var expr = Expression.Lambda(Expression.Property(pe, sortByProp), pe);
var d= expr.Compile();
IQueryable<Person> query = persons.AsQueryable();
List<Person> sortedList = query.OrderBy<Person, int>(expr).ToList();
It seems like you are trying to implement OrderBy dynamically using expression trees. You should try the following:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortProperty, ListSortDirection sortOrder)
{
var type = typeof(T);
var property = type.GetProperty(sortProperty);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
var typeArguments = new Type[] { type, property.PropertyType };
var methodName = sortOrder == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
var resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, Expression.Quote(orderByExp));
return source.Provider.CreateQuery<T>(resultExp);
}
and then you can call it as:
collection.OrderBy("Property on which you want to sort", ListSortDirection.Ascending);
I am new to linq c# , Following is my function
public static IQueryable<T> BuildWhereExpression<T>(this IQueryable<T> query, SearchAttributes searchModel)
{
string FilterField = searchModel.FilterField;
string FilterOperator = searchModel.FilterOperator;
string FilterValue = searchModel.FilterValue;
ParameterExpression ParamExp = Expression.Parameter(typeof(T), GlobalConstants.SearchExpressionName);
Expression InitialExp;
LambdaExpression FinalExp;
switch (FilterOperator)
{
case GlobalConstants.IsEqualTo:
if (FilterValue == "")
InitialExp = Expression.Call(Expression.PropertyOrField(ParamExp, FilterField), typeof(string).GetMethod("Contains"), Expression.Constant(FilterValue));
else
InitialExp = Expression.Equal(Expression.PropertyOrField(ParamExp, FilterField), Expression.Constant(FilterValue));
break;
case GlobalConstants.Contains:
{ // This is what i havd tried till now
//var Column = Expression.PropertyOrField(ParamExp, FilterField);
//var isNull = Expression.Equal(Column, Expression.Constant(null));
//Expression left = Expression.Call(Column, typeof(string).GetMethod("ToString", System.Type.EmptyTypes));
//Expression left = Expression.Call(pe)
}
InitialExp = Expression.Call(Expression.PropertyOrField(ParamExp, FilterField), typeof(string).GetMethod("Contains"), Expression.Constant(FilterValue));
break;
case GlobalConstants.StartsWith:
InitialExp = Expression.Call(Expression.PropertyOrField(ParamExp, FilterField), typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }), Expression.Constant(FilterValue));
break;
default:
InitialExp = Expression.Constant(true);
break;
}
FinalExp = Expression.Lambda<Func<T, bool>>(InitialExp, new ParameterExpression[] { ParamExp });
MethodCallExpression result = Expression.Call(typeof(Queryable), "Where", new Type[] { query.ElementType }, query.Expression, Expression.Quote(FinalExp));
return query.Provider.CreateQuery<T>(result);
}
The above code adds a condition for contains in a column dynamically.
Contains does not works for column containing null values.
How can i implement following logic
If table.ColumnValue is Null replace the column null with empty string then compair with the value in FilterValue
EDIT:
I mean how can i implement query as
coalesce(table.column,string.empty) == FilterValue
Please help me over this.
Thanks in advance.
The expression you are looking for is something like:
Expression<Func<T, bool>> exp = x => (x.FilterField ?? string.Empty).Contains(FilterValue);
that can be obtained with
var coalesce = Expression.Coalesce(
Expression.PropertyOrField(ParamExp, FilterField),
Expression.Constant(string.Empty))
so
InitialExp = Expression.Call(coalesce, typeof(string).GetMethod("Contains"), Expression.Constant(FilterValue));
Note that, considering future-proofing, I would always explicitly tell the .NET the parameters of the method I'm looking for:
typeof(string).GetMethod("Contains", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(string) }, null);
because you can't know if, in .NET ∞.0, they'll finally add an overload that supports a StringComparison :-)
I am using the Entity Framework, ASP.NET and C#3.5
I borrowed the following code to make sorting possible using a sortExpression from a GridView instead of the property of an entity:
public static IEnumerable<T> Sort<T>(this IEnumerable<T> source, string sortExpression)
{
string[] sortParts = sortExpression.Split(' ');
var param = Expression.Parameter(typeof(T), string.Empty);
var property = Expression.Property(param, sortParts[0]);
var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, typeof(object)), param);
if (sortParts.Length > 1 && sortParts[1].Equals("desc", StringComparison.OrdinalIgnoreCase))
{
return source.AsQueryable<T>().OrderByDescending(sortLambda);
}
return source.AsQueryable<T>().OrderBy(sortLambda);
}
The problem is that LINQ to Entities does not support casting to object. Instead of Func, I need the actual return type instead of object. I worked out how to do it:
public static IEnumerable<T> Sort<T>(this IEnumerable<T> source, string sortExpression)
{
string[] sortParts = sortExpression.Split(' ');
var param = Expression.Parameter(typeof(T), string.Empty);
var property = Expression.Property(param, sortParts[0]);
// NEW CODE HERE
Type propertyType = property.Type;
Type lambdaType = typeof(Func<,>).MakeGenericType(typeof(T), propertyType);
var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, propertyType), param);
//var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, typeof(object)), param);
if (sortParts.Length > 1 && sortParts[1].Equals("desc", StringComparison.OrdinalIgnoreCase))
{
return source.AsQueryable<T>().OrderByDescending(sortLambda);
}
return source.AsQueryable<T>().OrderBy(sortLambda);
}
The problem now is that if I have an Int32, it will not cast to object, which is still the return type. I worked around it like this:
public static IEnumerable<T> Sort<T>(this IEnumerable<T> source, string sortExpression)
{
string[] sortParts = sortExpression.Split(' ');
var param = Expression.Parameter(typeof(T), string.Empty);
var property = Expression.Property(param, sortParts[0]);
// New code here
Type propertyType = property.Type;
Type lambdaType = typeof(Func<,>).MakeGenericType(typeof(T), propertyType);
// NEWEST CODE HERE
var sortLambda = Expression.Lambda(lambdaType, Expression.Convert(property, propertyType), param);
//var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, propertyType), param);
//var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, typeof(object)), param);
if (sortParts.Length > 1 && sortParts[1].Equals("desc", StringComparison.OrdinalIgnoreCase))
{
return source.AsQueryable<T>().OrderByDescending(sortLambda);
}
return source.AsQueryable<T>().OrderBy(sortLambda);
}
This however does not compile any longer. The error is:
The type arguments for method 'System.Linq.Enumerable.OrderByDescending(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
The problem is that I do not want to specify the type arguments explicitly.
Does anyone know how to work around this or anyhow infer the TResult type from "propertyType"?
The approach used here, with the refinement here, should do what you need. By necessity it uses reflection to do the guts in the middle, but it works. Note also that Expression.GetFuncType and Expression.GetActionType can avoid some of the work in your approach.