This question already has an answer here:
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);
where
call without the contains bit? - Douglas Gaskell
You can have this extension method:
public static T GetPropertyValue<T>(this Product product, string propName)
{
return (T)typeof(Product).GetProperty(propName).GetValue(product, null);
}
Then:
IQueryable<Product> query = query.Where(x => x.GetPropertyValue<string>("ProductName").Contains("P100"));
Notice that this will not work with Entity Framework to query a database, but since you haven't tagged the question with entity framework, I'm not assuming you are using it
GetPropertyValue()
method on aProduct
object? There's no point in doing the conversion if it's not supported. - Jeff Mercado