Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Lambda Expression - Get property value from string [duplicate]

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?

like image 702
Rahul Avatar asked Dec 28 '25 13:12

Rahul


2 Answers

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);
like image 171
Aron Avatar answered Dec 31 '25 04:12

Aron


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

like image 45
Jcl Avatar answered Dec 31 '25 02:12

Jcl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!