从属性名作为字符串到List.Contains(x.Property)

本文关键字:Contains Property List 字符串 从属性 | 更新日期: 2023-09-27 18:15:48

我有这个:

// selectedOptions Contains a list of string constants
var selectedOptions = new List<string>(...); 
Expression<Func<T, bool>> condition = null;
switch (propertyName)
{
    case "Property1":
        condition = x => selectedOptions.Contains(x.Property1);
        break;
    case "Property1":
        condition = x => selectedOptions.Contains(x.Property2);
        break;
    case "Property3":
        condition = x => selectedOptions.Contains(x.Property3);
        break;
}

该条件将用作Linq to Entities中Where()的谓词。这个想法是EF沿着where Property1 in (...)的路线生成SQL。我不知道是否有更好的方法来做到这一点,但它是有效的。

我的问题是,我想取消这个开关,并有如下内容:

condition = x => selectedOptions.Contains(x.[propertyName]);

有可能吗?

从属性名作为字符串到List.Contains(x.Property)

是可能的:

var parameter = Expression.Parameter(typeof(T));
var containsMethod = typeof(List<string>).GetMethod("Contains");
var property = Expression.Property(parameter, propertyName);
var body = Expression.Call(Expression.Constant(selectedOptions), containsMethod, property);
condition = Expression.Lambda<Func<T, bool>>(body, parameter);