.net – 将Linq where条件添加到通用IQueryable

基本上,我想做的是:

var validValues = new List<int>() { 1, 2, 34 };

query = query.Where(item => validValues.Contains(item.Value));

除了我不知道它是什么类型,我想将其作为扩展方法:

public static IQueryable<T> Where<T>(this IQueryable<T> source, string propertyName, IList<int> accpetedValues)
{
   if (accpetedValues == null || !accpetedValues.Any() || string.IsNullOrEmpty(propertyName))
      return source;

   // HERE

   return source;
}

我发现这个帖子IQueryable Extension: create lambda expression for querying a column for a keyword
但这不是我想要的,我无法弄清楚如何使它适应我的情况……

最佳答案 这是带有通用有效值集合的动态表达式的更好版本:

    public static IQueryable<Tsource> Where<Tsource, Tproperty>(this IQueryable<Tsource> source, Expression<Func<Tsource, Tproperty>> property, IList<int> accpetedValues)
    {
        var propertyName = ((MemberExpression)property.Body).Member.Name;

        if (accpetedValues == null || !accpetedValues.Any() || string.IsNullOrEmpty(propertyName))
            return source;

        var item = Expression.Parameter(typeof(Tsource), "item");
        var selector = Expression.PropertyOrField(item, propertyName);
        var predicate = Expression.Lambda<Func<Tsource, bool>>(
            Expression.Call(typeof(Enumerable), "Contains", new[] { typeof(Tproperty) },
                Expression.Constant(accpetedValues), selector),
            item);
        return source.Where(predicate);
    }

用法:

query = query.Where(item => item.Value, validValues));
点赞