c# Lambda 表达式 - 从字符串中获取 属性 值

c# Lambda Expression - Get property value from string

考虑以下 lambda 表达式:

IQueryable<Product> query = query.Where(x => x.ProductName.Contains("P100"));

我需要将上面的代码转换成这样:

IQueryable<Product> query = query.Where(x => x.GetPropertyValue("ProductName").Contains("P100"));

这里我添加了一个伪方法GetPropertyValue("ProductName")来解释需求。 在上面的代码中,属性 应该在 运行 时间内解决。换句话说,我需要从字符串值访问 属性 例如 "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);

你可以有这个扩展方法:

public static T GetPropertyValue<T>(this Product product, string propName)
{
   return (T)typeof(Product).GetProperty(propName).GetValue(product, null);
}

然后:

IQueryable<Product> query = query.Where(x => x.GetPropertyValue<string>("ProductName").Contains("P100"));

请注意,这不适用于 Entity Framework 查询数据库,但由于您没有使用 entity framework 标记问题,我不假设您正在使用它