Consider following lambda expression:
IQueryable<Product> query = query.Where(x => x.ProductName.Contains("P100"));
I need to convert above code something like this:
IQueryable<Product> query = query.Where(x => x.GetPropertyValue("ProductName").Contains("P100"));
Here I have added a dummy method GetPropertyValue("ProductName")
to explain the requirement. In above code the property should be resolved in run-time. In other words I need to access the property from a sting value E.g "ProductName"
How can I do this?
var parameterExp = Expression.Parameter(typeof(Product), "type");
var propertyExp = Expression.Property(parameterExp, propertyName);
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValue = Expression.Constant(propertyValue, typeof(string));
var containsMethodExp = Expression.Call(propertyExp, method, someValue);
Expression<Func<Product, bool>> predicate = Expression.Lambda<Func<T, bool>>
(containsMethodExp, parameterExp);
var query = query.Where(predicate);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments