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

27 浏览
0 Comments

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

这个问题已经有答案了:

使用反射从字符串中获取属性值

考虑下面的lambda表达式:

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

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

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

这里我添加了一个虚拟方法GetPropertyValue(\"ProductName\")来解释需求。

在上面的代码中,属性应该在运行时解析。换句话说,我需要从一个字符串值中访问属性,例如\"ProductName\"

我该怎么做?

admin 更改状态以发布 2023年5月24日
0
0 Comments

你可以使用这个扩展方法:

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

然后:

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

注意,这个方法不适用于使用Entity Framework查询数据库的情况,但既然你没有标记问题使用的是Entity Framework,我就不假设你在使用它。

0
0 Comments
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> predicate = Expression.Lambda>
             (containsMethodExp, parameterExp);
var query = query.Where(predicate);

:这是一个包含加粗文本的段落。

0