1

我有这个:

// 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 (...). 我不知道是否有更好的方法来做到这一点,但它确实有效。

我的问题是我想消除开关并有一些类似的东西:

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

是否可以?

4

1 回答 1

1

是的,有可能:

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

这将手动构建表达式树。

于 2013-05-29T14:15:55.347 回答