1

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?


  • I mean I have to make this method more generic. According to my application logic I only have the property name as a string value. So i need to resolve the string as a property. - Rahul
  • What's your query processor? Will it even support using a GetPropertyValue() method on a Product object? There's no point in doing the conversion if it's not supported. - Jeff Mercado
  • You need to learn either Linq Expressions, or you need to use Dynamic Linq. - Aron
  • @DavidG This is a completely different question from the one you are referencing, given that using Reflection will not work with most Linq Providers. - Aron

2 답변


5

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);


  • Can this easily transferred to just a linq where call without the contains bit? - Douglas Gaskell
  • @DouglasGaskell What do you mean without the contains bit? The above code is for generating a pure Linq expression tree without any CLR. Which allows this query to run in most Linq Providers including non CLR backed providers like EF or nHiberate. - Aron

0

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


  • I'm using Odata V4 with Odata Client code generator. will this work? - Rahul
  • I never used it, I don't know, but if it's pertinent to the question (and it is), you should have specified it (or at least tagged the question) - Jcl

Linked


Related

Latest