Rah*_*hul 2 c# linq lambda iqueryable
考虑遵循lambda表达式:
IQueryable<Product> query = query.Where(x => x.ProductName.Contains("P100"));
Run Code Online (Sandbox Code Playgroud)
我需要转换上面这样的代码:
IQueryable<Product> query = query.Where(x => x.GetPropertyValue("ProductName").Contains("P100"));
Run Code Online (Sandbox Code Playgroud)
在这里,我添加了一个虚拟方法GetPropertyValue("ProductName")
来解释需求.在上面的代码中,属性应该在运行时解析.换句话说,我需要从sting值Eg访问该属性"ProductName"
我怎样才能做到这一点?
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);
Run Code Online (Sandbox Code Playgroud)